Skip to content

Laravel Where Condition Based On A Relationship Table

Reading Time: < 1 minute

Laravel PHP framework is a complete MVC tool to build any kind of website. It almost has all the required features a developer needs. For example, if you want to get results based on a relationship table it has some unique Where condition options to do that. Here is the easiest way you can find it.

Laravel Where Condition using Wherehas

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

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 }
See also  Good Coding Standards of PHP

Leave a Reply