$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
whereIn() Laravel Query with Example: whereIn() is used to check whether column contains value from the array or list. Basically, it is used to match column against list of values.
Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.
If you need to use sql wherein query in laravel then you can use with array. Laravel provide wherein() to use sql wherein query. in wherein() we just need to pass two argument one is column name and another if array of ids or anything that you want.
Searching Eloquent models Imagine you need to provide a search for users. Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With