user3653474
user3653474

Reputation: 3852

Search in the related model in Laravel

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

Answers (4)

Vision Coderz
Vision Coderz

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

tameemahmad shahzad
tameemahmad shahzad

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

  1. We are fetching the title which matches with the request
  2. 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

OMR
OMR

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

Sheetal Mehra
Sheetal Mehra

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

Related Questions