I want to use Eloquent's active record building to build a search query, but it is going to be a LIKE search. I have found the User::find($term)
or User::find(1)
, but this is not generating a like statement. I'm not looking for a direct answer, but if someone could at least give me a direction to look in that'd be great!
96
votes
laravel.com/docs/database/eloquent .. you can use documentation ıt is very clear.
- ytsejam
I've seen this page I just didn't see anything about searching with wildcards. I also didn't want to set up a regex in a foreach loop as there are hundreds of thousands of rows
- Jonathan
$email = DB::table('users')->where('id', '=', 1)->only('email');
- ytsejam
it is called fluent query builder in the docs.
- ytsejam
If I could mark the answer and your comment as the answer, I would. Thank you for getting me in the right direction
- Jonathan
5 Answers
241
votes
65
votes
If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent ORM:
public function scopeLike($query, $field, $value){
return $query->where($field, 'LIKE', "%$value%");
}
So then you can use this method in such way:
User::like('name', 'Tomas')->get();
29
votes
FYI, the list of operators (containing like and all others) is in code:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
Joel Larson's answer is correct. Got my upvote.
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.
18
votes
Use double quotes instead of single quote eg :
where('customer.name', 'LIKE', "%$findcustomer%")
Below is my code:
public function searchCustomer($findcustomer)
{
$customer = DB::table('customer')
->where('customer.name', 'LIKE', "%$findcustomer%")
->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
->get();
return View::make("your view here");
}