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.*']);
if($request->get('q')){
$query->where(function($query1) use ($request){
$query1->where('categories.title', 'like', '%'.$request->get('q').'%')
->orWhere('products.title', 'like', '%'.$request->get('q').'%');
});
}
My Answer:
>where('title', 'like', '%'.$search.'%')
>->orWhereHas('products', function($query) use ($search) {
$query->where('title', 'like', '%'.$search.'%');
})
>->get();
Rate this post
3 of 5 based on 3973 votesComments