CrtlAltDylan
4 years ago

Accessing specific subtypes of a polymorphic relationship

Posted 4 years ago by CrtlAltDylan

This is a general best practice kind of question. My application is a little more complex and I have found using polymorphic relationships really help you scale and normalize your database.

However sometimes it leads me to have to do things like this on some models:

User class extends Eloquent
{
    /**
     * A user has many transportations (Rides, Flights, Bus rides, etc)
     */
    public function transportations()
    {
        return $this->morphMany('Transportation', 'transportationable');
    }

    /**
     * I need to be able to grab all of the flights a user has
     */
    public function flights()
    {
        // Getting all transportations of the Flight type
        $flightTransportations = $this->transportations(function($transportation)
        {
            return $transportation->transportationable_type = 'Flight';
        })
        //Converting the collection to actual Flight objects not Transportation objects
        $flights = $flightTransportations->map(function($flightTransportation)
        {
            return Flight::find($flightTransportation->transportationable_id);
        });

        return $flights;
    }
}

As you can see this gets a little old after awhile. Is there a hasThrough method for polymorphic relationships that I'm not aware of?

Please sign in or create an account to participate in this conversation.