Mojtaba Mojtaba - 1 year ago 55
PHP Question

laravel 5.2 search in related entity

Suppose I have a Model called 'Commodity' which has category_id belongs to a category.

In Commodity.php I defined this relationship:

public function category(){
return $this->belongsTo('App\Category');

Now, I want to find the commodities which their category name include 'glass'

I tried this:

$items = Commodity::orderBy('id', 'desc')->category()->where('title', 'LIKE', '%glass%');

But it populates this error:

Call to undefined method Illuminate\Database\Query\Builder::category()

Answer Source

Please read official documentation that covers querying relations.

Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:

$users = App\User::with(['posts' => function ($query) {

    $query->where('title', 'like', '%first%');


So, regarding your question I'd suggest to try next:

$commodities = App\Commodity::with(['category' => function ($query) {

    $query->where('title', 'like', '%glass%');

}])->orderBy('id', 'desc')->get();