To explain this question better I'll just give an example:
Let's say I have a world records database and wish to create an api for it. Let's say I want to add a search
route that takes in GET
or POST
parameters (let's keep it simple and just say GET
for now). Is it possible to write a search
controller method which uses something like an array as a parameter to Eloquent's where
method while also utilizing a like
parameter (MySQL LIKE
)?
I have the following which works but only for exact values:
public function search()
{
$params = Input::all();
return Records::where($params)->get();
}
You should be able to:
public function search()
{
$params = Input::all();
$query = Records::newQuery();
foreach($params as $key => $value)
{
$query->where($key, 'LIKE', "%$value%")
}
return $query->get();
}
In the context of a scope, you can get fancier:
class User extends Eloquent {
public function scopeFilter($query, $input = null)
{
$input = $input ?: Input::all();
foreach($input as $key => $value)
{
if (Schema::hasColumn($this->getTable(), $key))
{
$query->where($key, 'LIKE', "%$value%")
}
}
return $query;
}
}
Then you can do:
$filtered = User::filter()->get();
Or
$filtered = User::filter(Input::only('name', 'age'))->get();