laravel querybuilder how to use like in wherein function
Asked Answered
P

3

30

$book = array('book1','book2'); $book array elements numbers are variable. it might have 2 element or 20 elements
I need to make a query like this:

select * from book where bookname like %book1% or bookname like %book2%

To make this query in laravel 5 there is an option :

$name = DB::Table('bookinfo')
          ->select('*')
          ->wherein('bookname',$book)
          ->get();

but it use = operator I need to use like operator

Pedant answered 17/12, 2015 at 8:30 Comment(0)
P
46

Thanks everyone for helping me but i solved it by doing:

$book = array('book2','book3','book5');  

$name = DB::Table('bookinfo')
        ->select('BookName', 'bookId')                
        ->Where(function ($query) use($book) {
             for ($i = 0; $i < count($book); $i++){
                $query->orwhere('bookname', 'like',  '%' . $book[$i] .'%');
             }      
        })->get();
Pedant answered 17/12, 2015 at 8:58 Comment(1)
This is equivalent to @goldlife's answer except yours is more elegant.Calmas
W
10

For a dynamic query with 1 or n elements use your statement as a collection: For the "like" you can use a Raw statement:

$collection = DB::Table('bookinfo')->select('*');
foreach($book as $key => $element) {
    if($key == 0) {
        $collection->where(DB::raw('bookname like %'.$element.'%'));
    }
    $collection->orWhere(DB::raw('bookname like %'.$element.'%'));
}
$name = $collection->get();

http://laravel.com/docs/5.1/queries

Raw Expressions

or you can use it in this way:

$collection = DB::Table('bookinfo')->select('*');
foreach($book as $key => $element) {
    if($key == 0) {
        $collection->where('bookname', 'like', '%'.$element.'%');
    }
    $collection->orWhere('bookname', 'like', '%'.$element.'%');
 }
 $name = $collection->get();
Weiman answered 17/12, 2015 at 8:38 Comment(1)
$book array elements numbers are variable. it might have 2 element or 20 elementsPedant
P
-4
$name = DB::Table('bookinfo')
          ->select('*')
          ->where('bookname','LIKE','%'.$book[0].'%')
          ->orWhere('bookname','LIKE','%'.$book[1].'%')
          ->get();
Pacifa answered 17/12, 2015 at 8:47 Comment(1)
This solution will only work when $book array contains only 2 members. I will not work when $book array has more than 2 members as "it might have 2 element or 20 elements" is mentioned in question.Cabernet

© 2022 - 2024 — McMap. All rights reserved.