samedi 5 janvier 2019

Override eloquent Relation Create Method

I want to override create method, but with relation,it didn't touch the create method.

There are Two Models:

class User extends Model
{
    public function user_detail()
    {
        return $this->hasOne(UserDetail::class);
    }
}


class UserDetail extends Model
{
    public static function create(array $attributes = [])
    {
        //I was trying to do something like
        /*
        if(isset($attributes['last_name']) && isset($attributes['first_name']))
        {
            $attributes['full_name']=$attributes['first_name'].' '.$attributes['last_name'];
        }
        unset($attributes['first_name'],$attributes['last_name']);
        */

        Log::debug('create:',$attributes);
        $model = static::query()->create($attributes);
        return $model;
    }
}

When I use UserDetail::create($validated), and there is a log in laravel.log, so I know the code touched my custom create method.

But if I use

$user = User::create($validated);
$user->user_detail()->create($validated);

There is no log in laravel.log, which means laravel didn't touch the create method, then how I supposed to do to override create method under this circumstance?(I'm using laravel 5.7)



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2AqtkJ9
via IFTTT

Aucun commentaire:

Enregistrer un commentaire