1

Upgraded to L5 and loving it! However currently facing an issue with polymorphing a relationship. In my userable column in the Users table I need to include the namespaced value (e.g. "App\Employee" rather than just "Employee") for the polymorph relationship to work.

Feels like I am missing something.. How do I avoid forcing to store namespaced values in the table? :)

PS: Well aware others are struggling with similar issues (e.g. Laravel 5 namespaces) but have not seen anything relating to avoiding to store the namespacing in the tables..

BaseController

<?php namespace App\Http\Controllers;
use App\Client;
use App\User;
...

HomeController

$user = User::with('userable')->get();

foreach ($user as $u){
    var_dump($u->userable->mobile);
}

User model

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

Client model

public function user()
{
    return $this->morphOne('App\User', 'userable');
}

Employee model

public function user()
{
    return $this->morphOne('App\User', 'userable');
}
Community
  • 1
  • 1
Peder Wessel
  • 646
  • 1
  • 9
  • 23

1 Answers1

0

Ended up creating a separate column in the User table. One for role (e.g. Admin, Employee etc.) and another column for the userable_type (e.g. '\App\Admin')

protected $morphClass 

Seemed promising (Polymorphic Eloquent relationships with namespaces) but has known bugs in the inversed relationship (Laravel 5 namespaces)

And even the latter does not work quite elegantly - so until it is resolved, I'll go for the two column approach - hopes this helps others!

Community
  • 1
  • 1
Peder Wessel
  • 646
  • 1
  • 9
  • 23