Filter in two related model in laravel

  eloquent, laravel, php, relational-database

I have two model named as Product and Category. In the products table i have category_id as as a foreign key of categories. Both table have title column. I want to search on both title and when it is related to categories table then all products of that category will come in result but when it is related to products table then only those products come which are related to query.

I tried it like :

$query = Category::with('products')->select(['products.*']);

    $query->where(function($query1) use ($request){
        $query1->where('categories.title', 'like', '%'.$request->get('q').'%')
        ->orWhere('products.title', 'like', '%'.$request->get('q').'%');

Source: Laravel

Leave a Reply