Telanor
Telanor

Reputation: 4429

Laravel 4: Save polymorphic relationship

I'm trying to save a polymorphic relationship in laravel and can't get it to work. I either get this error: Call to undefined method Illuminate\Database\Query\Builder::save() if I do $user->provider()->save($provider)

Or I get

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userable_type' in 'field list' (SQL: insert into 'providers' ('user_id', 'userable_type', 'userable_id') values (16, Provider, 16))

if I switch it around and do $provider->user()->save($provider); as suggested in Call to undefined Builder::save() when saving a polymorphic relationship

From what little documentation I could find on polymorphic relationships, it seems the userable_type/id stuff goes in the parent table, and since User is my parent table, rather than Provider, the 2nd method seems to be the wrong way to do it.

At a guess I'd say the problem is with my morphTo/morphOne methods, but I've no clue how to fix them since the documentation for those methods has nothing to say about their parameters. My provider table might be set up a bit differently from what laravel expects, since it doesn't have an incremental id field as the primary key; the primary key is the foreign key and is named user_id.

This is my register code:

public function postRegister()
{
    $input = Input::all();
    $user = $this->user;
    $validator = Validator::make($input, $user::$rules);

    if($validator->passes())
    {
        $user->username = $input['username'];
        $user->email = $input['email'];
        $user->password = Hash::make($input['password']);
        $user->save();

        if($input['account_type'] == 0)
        {
            $provider = new Provider();
            $provider->user_id = $user->id;

            //$provider->user()->save($provider);
            $user->provider()->save($provider);
        }

        return 'Success';
    }
    else
    {
        return Redirect::back()->withInput($input)->withErrors($validator->messages());
    }
}

User model:

<?php

class User extends Validatable implements UserInterface, RemindableInterface
{
    use UserTrait, RemindableTrait;

    protected $table = 'users';

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

Provider Model:

<?php

class Provider extends Validatable
{
    protected $table = 'providers';
    protected $primaryKey = 'user_id';

    public $timestamps = false;

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

Upvotes: 1

Views: 404

Answers (1)

Walid Ammar
Walid Ammar

Reputation: 4126

You can call it like this:

$provider->user()->save($user);

Upvotes: 3

Related Questions