mercredi 1 août 2018

Laravel updating multiple relationships with 1 save

I have seen things around the internet related to this, but either I cant quite seem to understand it or the answer is very old and related to an older version of laravel, so could someone explain to me how to do this?

So lets say I have a master model of users, and my users model has multiple relationships like so

public function contacts(){
    return $this->hasMany('App\Models\Users\UserContacts', 'user_id', 'id');
}

public function discounts(){
    return $this->hasMany('App\Models\Users\UserDiscounts','user_id', 'id');
}

Then inside an update function, i'm updating the user and relationships like this

//Get the user to update
$user = User::findOrFail($id);
$user->name = $request->name;
$user->age  = $request->age;
$user->discounts->amount = $request->discount_amount;
$user->discounts->start_date = $request->discount_start_date;
$user->contacts->name = $request->contact_name;
$user->contacts->email = $request->contact_email;

How do I save this so that it saves the user model and all the relationships?

$user->save(); //Only works for user model
$user->update(); //Only works for user model
$user->discounts->save(); //Only works for discount model

I have a very large list of relationships, and ideally I would like to be able to save them all with 1 command. Is this possible?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire