Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining AND/OR eloquent query in Laravel

Tags:

How can I write following or similar kind of queries using Eloquent?

SELECT * FROM a_table WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1 AND d = 5

I couldn't combine AND/OR in the way I wanted by chaining where & or_where functions.

like image 209
SUB0DH Avatar asked Mar 27 '13 06:03

SUB0DH


2 Answers

You can nest where clauses : http://laravel.com/docs/database/fluent#nested-where

Model::where(function($query)
{
    $query->where('a', 'like', 'keyword');
    $query->or_where('b', 'like', 'keyword');
})
->where('c', '=', '1');

This should produce : SELECT * FROM models WHERE (a LIKE %keyword% OR b LIKE %keyword%) AND c = 1

like image 174
Florent Poujol Avatar answered Sep 18 '22 05:09

Florent Poujol


For a more accurate answer to the example:

$val = '%keyword%';

A_Table_Model::where(function($query) use ($val)
{
    $query->where('a', 'like', $val);
    $query->or_where('b', 'like', $val);
})
->where('c', '=', 1)
->where('d', '=', 5)
->get();

Note: This is Laravel 3 syntax, use camelCase orWhere() for Laravel 4

like image 23
aowie1 Avatar answered Sep 19 '22 05:09

aowie1