Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gadreel's avatar

Laravel 4 - Eloquent Polymorphic Question

I have a polymorphic table name "Unit" with the following columns

user_id

serial_id

serial_type

public function serial()
    {
        return $this->morphTo();
    }

And I have other tables VSUnit, BBUnit, CLUnit all these tables are linked with the Unit table using polymorphic. The reason I did it like this is because the above 3 tables have different columns between each other and the only common thing is the serial id. So using something like "Unit::find('10000')->serial" I will get either VSUnit or BBUnit or CLUnit model.

public function unit()
    {
        return $this->morphOne('App\Models\Unit', 'serial');
    }

What I cannot figure out is this. When I want to ask the question which units a User has I want to be able again get an Eloquent Collection with only the related models. The only way I came with it's this which gets the Units based on the user_id and then using the serial to get the related model.

public function units() {
        $units = [];
        foreach($this->hasMany('App\Models\Unit', 'user_id')->get() as $unit) {
            $units[] = $unit->serial;
        }
        return $units;
    }

Is there another way to accomplish this?

0 likes
0 replies

Please or to participate in this conversation.