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!
Using Eloquent you can perform a search like this: User::query() ->where('name', 'LIKE', "%{$searchTerm}%") ->orWhere('email', 'LIKE', "%{$searchTerm}%") ->get();
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.
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.
You're able to do database finds using LIKE with this syntax:
Model::where('column', 'LIKE', '%value%')->get();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With