SupaMonkey
SupaMonkey

Reputation: 884

Laravel MorphMany Relationship - What am I missing?

I have the defaults users table which I've altered to have userable_type and userable_id. I have various models, eg BursaryAdministrator and BursaryProvider and users can belong to either.

BA/BP Model:

public function users() {
    return $this->morphMany('App\Users', 'userable');
}

Users Model:

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

During my migration, I've created a default BursaryAdministrator and BursaryProvider and a couple of users. I want to assign them to each:

$bp = \App\BursaryProvider::first();
$user = User::find(2);
$bp->users()->associate($user);

$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$ba->users()->associate($user);

However, they're not linking as the userable_type / userable_id fields are null. I've tried both 'associate' and 'attach'. Whats the correct what to do this?

Upvotes: 0

Views: 84

Answers (2)

SupaMonkey
SupaMonkey

Reputation: 884

Ok, so this was the correct way at the end of the day:

    $bp = \App\BursaryProvider::first();
    $user = User::find(2);
    $user->userable()->associate($bp);
    $user->save();

    $ba = \App\BursaryAdministrator::first();
    $user = User::find(3);
    $user->userable()->associate($ba);
    $user->save();

Thanks to @dparoli for pointing me in the right direction.

Upvotes: 1

dparoli
dparoli

Reputation: 9171

You could try to save() the user after association, i.e.:

$bp = \App\BursaryProvider::first();
$user = User::find(2);
$bp->users()->associate($user);
$user->save()

$ba = \App\BursaryAdministrator::first();
$user = User::find(3);
$ba->users()->associate($user);
$user->save()

Upvotes: 1

Related Questions