Mihai.N
Mihai.N

Reputation: 49

How to use Polymorphic Relations in Laravel with all rows?

I'am new on Laravel, i use laravel 5.4 version. I have next scenario: i have one table for users where i put only username and pass, and two other tables employees and partners, where i keep all data for users like name, address, email, phone....

Tables structure:

users - id|username|password|userable_id|userable_type
employees - id|name|phone|email|salary|position|departamnet
partners - id|name|companyname

In User model:
class User extends Authenticatable
{
        public function userable(){
        return $this->morphTo();
    }
}

Class Model:
    class Employee extends Model
    {
        protected $fillable = [];
        public function users()
        {
            return $this->morphOne('App\User', 'userable');
        }
    }
Partner Model:
class Partner extends Model
{
    protected $fillable = [];
    public function users()
    {
        return $this->morphOne('App\User', 'userable');
    }
}

Now if i execute this (App\User::first()->userable )in tinker will return data from Employee/Partner only for the first user. for all() or get() methods will return this:

App\User::all()->userable Exception with message 'Property [userable] does not exist on this collection instance.' App\User::get()->userable Exception with message 'Property [userable] does not exist on this collection instance.'

It is any change to make this to work for all users list? PS: in users table on userable_type i have, a Model, and on userable_id i have row id that corresponds with model, for example Employee and 1. Thanks in advance.

Upvotes: 0

Views: 752

Answers (1)

JeffBeltran
JeffBeltran

Reputation: 739

I believe since you are getting a collection of all users, the issues is that you will need to eager load the relationships in order to get what you are looking for

App\User::with('userable')->get();

I'm not at my workstation to test this atm, but that should work if memory serves me right. I'll update this when i can test it

Upvotes: 1

Related Questions