Max Sangster
Max Sangster

Reputation: 69

How do I query a table with conditions from related table with Laravel 5

I have two tables,

table users: id, name, etc

table videos: id, user_id, etc

Model: Video

public function user()
{
    return $this->belongsTo('App\Models\User');
}

I want to select all videos where it is owned by the user "Max".

I have tried thing like the following:

$Videos = \App\Models\Video::with('user')->where('user.name','=','Max')->get();



Unknown column 'user.name' in 'where clause' (SQL: select * from `videos` where `videos`.`deleted_at` is null and `user`.`name` = Max)

Thanks!

Upvotes: 3

Views: 10801

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

That's what whereHas is for:

$Videos = \App\Models\Video::with('user')->whereHas('user', function($q){
    $q->where('name','=','Max');
})->get();

Upvotes: 18

Related Questions