SAVE THE MODEL AND ALL OF ITS RELATIONSHIPS ONE GO

Mar 01, 2024 Copy Link

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.

Share via

Mahmoud Ramadan

Mahmoud Ramadan

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

Most recent

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using...

    FREE

  • What is SQL Injection

    What is SQL Injection

    FREE

  • Leveraging virtual generated columns in MySQL using Laravel

    Leveraging virtual generated col...

    FREE