Search code examples
phplaravelsearchlaravel-5.3eloquent

How can I search with belongsto laravel?


My query to search for a username in a store listing is as follows:

$data = Store::join('users AS b', 'b.id', '=', 'stores.user_id')
             ->where('b.name', 'like', '%hazard%')
             ->paginate();

It works. But I use join to do it.

How can I do it using belongto?

My store model is like this :

class Store extends Model
{   
    protected $fillable = ['name', 'user_id', ...];
    public function user()
    {
        return $this->belongsTo(User::class,'user_id', 'id');
    }
    ...
}

Solution

  • Use whereHas():

    Store::whereHas('user', function($q) use($username) {
            $q->where('name', 'like', '%'.$username.'%');
        })->paginate(5);