Using a single array to pass multiple WHERE clauses (using LIKE)

Theory

It was discussed that you can use the following code to pass multiple WHERE clauses into a single where() method in Laravel Eloquent:

 $condition = array('field_1' => 'value_1', 'field_2' => 'value_2'); $users = User::where($conditon)->get(); 

The above code simply associates the key-value pairs of the array with AND , generating this:

 SELECT * FROM `users` WHERE field_1 = value_1 AND field_2 = value_2; 

Problem

Key-value pairs over the base on equality. Is it possible to use the same implementation for strings, where instead of = we use LIKE ?

An abstract example of what I mean:

 $condition = array( array('field_1', 'like', '%value_1%'), array('field_2', 'like', '%value_2%') ); $users = User::where($conditon)->get(); 

This can be done using several ->where(...) . Is this possible with passing a single array though?

+7
php sql-like eloquent laravel where
source share
1 answer

No, not at all. But internally, Laravel just does it with a loop.

Illuminate\Database\Query\ Builder@where

 if (is_array($column)) { return $this->whereNested(function($query) use ($column) { foreach ($column as $key => $value) { $query->where($key, '=', $value); } }, $boolean); } 

I suggest you do something like this:

 $condition = array( 'field_1' => '%value_1%', 'field_2' => '%value_2%' ); $users = User::where(function($q) use ($condition){ foreach($condition as $key => $value){ $q->where($key, 'LIKE', $value); } })->get(); 
+14
source share

All Articles