Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Eloquent where and orwhere

i try to get results from table with multiple where and/or clauses. But I am not receiving the good result!

$queries = journal::where(function($query)
{
$term =Input::get('text');
$query->where('titre', 'like', '%'.$term.'%')
    ->where('etat','!=','9')
    ->where('type', 0)
    ->orWhere('type', 1);
})->take(10)->get();    
like image 362
visulo Avatar asked Nov 30 '22 22:11

visulo


2 Answers

You should make your query like this:

$query->where('titre', 'like', '%'.$term.'%')
    ->where('etat','!=','9')
    ->where(function ($query) {
            $query->where('type', 0)
                  ->orWhere('type', 1);
        })

if you necessary wanna use orWhere otherwise use whereBetween. Reference Here

like image 81
Abhay Maurya Avatar answered Dec 13 '22 19:12

Abhay Maurya


You can use same query there compare with dynamic value using following way:

$valSearch='abcd';
$query->where('field1', 'like', '%'.$val1.'%')
    ->where('field2','!=','2')
    ->where(function ($query) use ($valSearch) {
            $query->where('field3', $valSearch)
                  ->orWhere('field4', $valSearch);
        })

The query will execute as :

field1 like '%{$val1}% AND field2 != 2 AND (field3='abcd' OR field4='abcd')

It may helpfull to some one for later use. Reference Here

like image 43
bharat Avatar answered Dec 13 '22 19:12

bharat