Trake101's avatar

Laravel 5 Polymorphic Broken?

I'm trying to create polymorphic relationships in L5, but they're not working the same way they did in L4.

For example, I have an accounts table with owner_id and owner_type as my polymorph columns, in L4 the owner_type would be set as user and everything worked perfectly, however, in L5 the only way I can get it to work is to use the model's namespace and set the owner_type to App\User.

Has anyone else encountered this and found a solution to it other than using the model's namespace?

0 likes
2 replies
chrisgeary92's avatar
Level 13

You can setup an alias for this class. First you need to add the morphClass property to your model(s)

<?php namespace Acme\Users;

use Illuminate\Database\Eloquent\Model;

class User extends Model {

    protected $table = 'users';

    /**
     * The class name to be used in polymorphic relations.
     *
     * @var string
     */
    protected $morphClass = 'User';
}

Then within the config, add a new class alias for 'User' like this:

'aliases' => array(
    //...
    'User' => '\Acme\Users\User',
)
1 like
Trake101's avatar

Awesome, using the morphClass alone worked, no need to alias. Thanks a ton!

Please or to participate in this conversation.