Reputation: 3852
I have post table like this :
id | post_title | category_id
and this is category table
id | category_title
this is the relation between these two which is inside post model :
public function category()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
I want to get the record of post table where category_title or post_title matches the keyword entered by user.
I'm retrieving data something like:
Post::where(['title'=>$request->title])->with('category')->paginate(10);
but here it is only fetching Post title but i also want it to search it in category title.
Any help is highly appreciated.
Upvotes: 1
Views: 54
Reputation: 8078
Post::->where('title', 'like', '%'.$request->title.'%')->with(['category' => function($query) use ($request){
$query->where('category_title', 'like', '%'.$request->title.'%');
}])->paginate(10);
Upvotes: 0
Reputation: 577
Post::where('title', 'like', '%'.$request->title.'%')->with(['category' => function($query) use ($request){
$query->where('category_title', 'like', '%'.$request->title.'%');
}])->paginate(10);
In the above code snippet
with(['category' => function($query) use ($request)
: laravel matches the result into relationship using closure function which accepts one parameter $request
and again we are filtering the relationship with this parameter $request->title which is coming through Request $request
You can use the code above or you can make a scope for reusability.
Upvotes: 1
Reputation: 12218
you should use orWhereHas:
Post::where(['title' => $request->title])->
orWhereHas('category',function ($query)use($request){
$query->where('category_title',$request->title);
})->with('category')-> paginate(10);
Upvotes: 0
Reputation: 518
Try this:-
$keyword = $request->input('title');
Post::with('category')
->where('title', 'like','%'.$keyword.'%')
->orWhere('category.category_title','like','%'.$keyword.'%')
->paginate(10);
Upvotes: 0