Eloquent where condition based on a "belongs to" relationship Eloquent where condition based on a "belongs to" relationship laravel laravel

Eloquent where condition based on a "belongs to" relationship


You may try this (Check Querying Relations on Laravel website):

$movies = Movie::whereHas('director', function($q) {    $q->where('name', 'great');})->get();

Also if you reverse the query like:

$directorsWithMovies = Director::with('movies')->where('name', 'great')->get();// Access the movies collection$movies = $directorsWithMovies->movies;

For this you need to declare a hasmany relationship in your Director model:

public function movies(){    return $this->hasMany('Movie');}

If you want to pass a variable into function($q) { //$variable } then

function($q) use ($variable) { //$variable }