Search code examples
phplaravelormeloquentrelationships

Laravel get all the models with relations


I can't find how to get all of the elements with relations to another element using Eloquent in Laravel. I have Substances and Contents and want all the contents related to the substances with name 'subst'.

My relation Substance - Content:

public function relation () 
{
    return $this->belongsToMany('Substance', 'contents_substances', 'id_contents', 'id_substances');
}

public function relation () 
{
    return $this->belongsToMany('Content', 'contents_substances', 'id_contents', 'id_substances');
}

I know I can get all the contents related to one substance:

$content = Substance::find(1)->relation()->get();

but is possible to get all the contents related to a group of substances?

something like:

$sub = Substance::where('name', '=', 'subst'); // get all the substances with that name
$contents =$sub->relation()->get(); // ???

Any help is appreciated!


Solution

  • The easiest is to start the query from the other angle. In this case from Content. whereHas will then add a constraint based on the substances relation:

    $contents = Content::whereHas('substances', function($q){
        $q->where('name', 'subst');
    })->get();