mardi 26 janvier 2016

Add relation to Eloquent Model before create it

I have 2 related Models. They are linked using MorphOne relationship. First Model is User:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    /**
     * Get all of the owning description models.
     */
    public function description()
    {
        return $this->morphTo();
    }
}

And second one is associated User type, which in our example is Trainer:

class Trainer extends Model
{
    /**
     * Get user, which trainer belongs to.
     */
    public function user()
    {
        return $this->morphOne('App\Models\Users\User', 'description');
    }

    /**
     * Event listeners
     */
    public static function boot()
    {
        parent::boot();

        static::created(function($item)
        {
            event(new TrainerCreated($item));
        });
    }
}

As you can see, I try to use Events for different User types. Inside those Events I want to access associated User Model, like so: $trainer->user But I cannot find right order to save those Models. What I have for now:

class AuthController extends Controller
{
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $user = Users\User::create([
            'name' => $data['name'],
            'surname' => $data['surname'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        switch ($data['type'])
        {
            case "trainer":
                $supertype = Users\Trainer::create();
                break;

            default:
                $supertype = Users\Visitor::create();
                break;
        }
        if ($supertype)
        {
            $supertype->user()->save($user);
        }
        return $user;
    }
}

Which throw me error, that I Trying to get property of non-object I also try another way, which seems more logical:

    switch ($data['type'])
    {
        case "trainer":
            $supertype = new Users\Trainer;
            break;

        default:
            $supertype = new Users\Visitor;
            break;
    }
    if ($supertype)
    {
        $user->description()->associate($supertype);
        $supertype->save();
    }

Which throws another error Class '' not found.

I tried multiple other ways, like manually setting ids, but they all throw different errors and not associate models properly. Maybe manually set both description_id and description_type will help, but I don't have id to set at this point.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire