Search code examples
phpeloquentlaravel-5mass-assignment

Laravel: Mass assignment insert new record or update exisiting


I have a User model and a UserInfo model. they are a one to one relationship.

When a user signs up, he then goes ahead to fill a very large form with more info. That is contained in the user_info table, represented by UserInfo model.

I currently do this

$user->user_info()->create($request->all());

it works but if it is run the second time, it creates andother UserInfo record for the same user.

Is there a way i can do it so that if the UserInfo record already exists for this user, it only updtes the exisiting one

Is there a method like updateOrCreate that can work with Mass Assignment like this?

So that if the UserInfo record already exist on this User, it just updates with these new values


Solution

  • You can achieve updateOrCreate functionality by using updateOrCreate() method.
    Usage:

    Model::updateOrCreate(
       ['primary_key' => 8],
       ['field' => 'value', 'another_field' => 'another value']
    );
    

    In your case, you can use fit in following way:

    $user->user_info()->updateOrCreate(['id'=>$user->id],$request->all());
    

    In place of id in ['id'=>$user->id] use the name of your model's primary key.