Laravel 5 Eloquent where and orwhere
Asked Answered
C

3

5

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();    
Cyndicyndia answered 27/3, 2017 at 10:4 Comment(5)
can you clarify what is failing? I do notice that you use the $text variable instead of $term.Matchlock
You didnt use the '$term' variable in your query. Is it intentional?Flashcube
I do not receive the good result!Cyndicyndia
Sorry typo error!Cyndicyndia
and you still not getting good result?Flashcube
D
3

Use whereBetween() instead.

$queries = journal::where(function($query)
{
    $term =Input::get('text');
    $query->where('titre', 'like', '%'.$text.'%')
        ->where('etat','!=','9')
        ->whereBetween('type', [0, 1]);
})->take(10)->get(); 

https://laravel.com/docs/5.4/queries - Additional Where Clauses

Decathlon answered 27/3, 2017 at 10:9 Comment(0)
U
14

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

Urey answered 27/3, 2017 at 10:15 Comment(1)
+1 for actually answering the question that was asked. Answering the question asked is helpful to folks googling a specific thing.Winnah
W
6

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

Welldressed answered 1/12, 2017 at 11:5 Comment(0)
D
3

Use whereBetween() instead.

$queries = journal::where(function($query)
{
    $term =Input::get('text');
    $query->where('titre', 'like', '%'.$text.'%')
        ->where('etat','!=','9')
        ->whereBetween('type', [0, 1]);
})->take(10)->get(); 

https://laravel.com/docs/5.4/queries - Additional Where Clauses

Decathlon answered 27/3, 2017 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.