Save the Model and All of its Relationships One Go

Mar 01, 2024

Let's imagine that we have a user who has many posts, and we wanna update the name with his first post title, so you may think of using the traditional way:

 

use App\Models\User;

$user = User::first();

$user->name = 'The First Change Of Name';
// $user->posts[0]->title = 'The First Change Of Title';
$user->posts->first()->title = 'The First Change Of Title';

// First, update the early post through his parent
$user->posts->first()->save();
// Then, update the parent itself
$user->save();

 

If you reverse the two lines of saving the child and his parent by miskate you will get the same result back.

 

So, the previous way will accomplish the task well, but Laravel introduces an amazing way to do so:

 

use App\Models\User;

$user = User::first();

$user->name = 'The Second Change Of Name';
// $user->posts[0]->title = 'The Second Change Of Title';
$user->posts->first()->title = 'The Second Change Of Title';

$user->push();

 

Woow, the task has been completed in a nutshell 🤵

 

It's IMPORTANT to use the Database Transactions in such a previous situation.

AI Assistant

Summarize, simplify, and ask questions about this content using your preferred AI provider.

Text Tools

Generate cleaner and easier-to-read versions of this content instantly

Have a Question?

Ask anything related to this content and get a focused AI-generated answer.

0/500
Mahmoud Ramadan
Author

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.