Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Eloquent ORM in Laravel to perform search of database using LIKE

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!

like image 489
Jonathan Avatar asked Nov 14 '12 20:11

Jonathan


People also ask

How do you use like in eloquent?

Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();

What is eloquent ORM in Laravel example?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.

Which ORM Laravel is used for handling DB queries?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database.


2 Answers

You're able to do database finds using LIKE with this syntax:

Model::where('column', 'LIKE', '%value%')->get(); 
like image 69
Joel Larson Avatar answered Oct 04 '22 20:10

Joel Larson


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(); 
like image 23
Yaroslav Avatar answered Oct 04 '22 18:10

Yaroslav