Thursday, April 13, 2017

Flatten Laravel Eloquent Collection relationships

I am using the following database structure:

movie
   - id
   - title

director
   - id
   - name

movie_director
   - director_id    - movie_id

The models are set up like this:

Movie.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model
{
    public $table = "movie";

    /**
     * The roles that belong to the user.
     */
    public function directors()
    {
        return $this->belongsToMany('App\Director', 'movie_director');
    }
}

Director.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Director extends Model
{
    public $table = "director";

    /**
     * The roles that belong to the user.
     */
    public function movies()
    {
        return $this->belongsToMany('App\Movie', 'movie_director');
    }
}

So there is a many-to-many relationship between a movie and a director.

On the detail page of a movie I would like to post other movies of the directors of the original movie.

    $movie = Movie::with('directors.movies')->find(1);

That gives me all the data I need, but to get a complete list of movies I would have to loop through the directors collection and then loop through the movies collection inside that director. Isn't there a faster/easier way to do this?



via Lloyd

Advertisement