guidsen
guidsen

Reputation: 2393

Eloquent query scope on relationship

I have two models called Page and User and I've set up the Eloquent relation as follows:

public function user() {
  return $this->belongsTo('User')
}

When I dd(Page::with('user')->get()) I get the right result. But now I want to have a search filter on this result.

I've used a scopeSearch but I'm not sure how to search on the resultset.

At the moment I have a scope like this:

public function scopeSearch($query, $search) {
  $query->where('username', 'LIKE', '%'.$search.'%')
     ->orWhere('name', 'LIKE', '%'.$search.'%')
}

So when I Page::with('user')->search('Test')->get() it is not working. The problem (probably) is that the username column is part of the User table and the name is part of the Page table.

How would I be able to use a scope or something familiar, to search on the resultset, without repeating it in most of the queries?

Upvotes: 2

Views: 6053

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

You need to create scopeSearch in User model and you should use it this way:

$posts = Page::with('user')->whereHas('user', function($q) use ($search)
{
    $q->search($search);

})->get();

Upvotes: 6

Related Questions