Using Eloquent ORM in Laravel to perform database lookup using LIKE

I want to use active record creation to create a search query, but it will be a LIKE search. I found User::find($term) or User::find(1) , but this does not create a similar statement. I'm not looking for a direct answer, but if someone can at least give me a direction to look, it will be great!

+79
sql-like orm eloquent laravel
Nov 14 '12 at 20:29
source share
5 answers

You can search a database using LIKE using this syntax:

 Model::where('column', 'LIKE', '%value%')->get(); 
+204
Nov 14
source share

If you need to use LIKE often, you can simplify this problem a bit. In a model that inherits Eloquent ORM, a custom like () method can be created:

 public function scopeLike($query, $field, $value){ return $query->where($field, 'LIKE', "%$value%"); } 

So you can use this method this way:

 User::like('name', 'Tomas')->get(); 
+54
Oct 19 '14 at 16:54
source share

FYI, the list of operators (containing like everyone else) is in the code:

 /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php protected $operators = array( '=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp', ); 

Denial of responsibility:

Joel Larson's answer is correct. Received my contribution.

I hope this answer sheds more light on what is available through the Eloquent ORM (pointing people in the right direction). Although the link to the documentation would be far better, this link turned out to be elusive.

+24
Nov 13 '14 at 6:00
source share

Use double quotes instead of single quotes, for example:

 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"); } 
+12
Dec 19 '14 at 2:18
source share

If you don't like double quotes like me, this will work for you with single quotes:

 $value = Input::get('q'); $books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get(); return view('pages/search/index', compact('books')); 
+1
May 30 '17 at 21:44
source share



All Articles