Laravel Eloquent updateOrCreate() Method

Hello Artisans, today I'll discuss about one of the handy method called updateOrCreate(). This method help us to write better and clean code in a shorter way. Let's see what actually does this method and uses of this handy method.

updateOrCreate() Method

public function withUpdateOrCreate()
    {
        $email = '[email protected]';

        $user = User::updateOrCreate(
            [ 'email' => $email ],
            [ 'name' => 'Tanvir Ahmed Hera' ]
        );

        dd($user);
    }

So here, what actually does the updateOrCreate() method? First of all, as we see on the above example that it'll accept two parameters. From the first parameter it'll search in the database for given condition if a row exist or not. If exists it'll update that row with the given 2nd parameter. So, if we consider with our given code, First of all it'll search in the users table where email is "[email protected]", if it'll find then it'll update the name of the searched one. And if no matching records found then it'll just create a new row with given name and email.

without updateOrCreate() Method

In the earlier we used to write the below logics for the above scenerio.

public function withoutUpdateOrCreate()
    {
        $email = '[email protected]';
        $user = User::where('email', $email)->first();

        if ($user) {
            $user->update([
                'name' => 'Tanvir Ahmed Hera',
            ]);
        } else {
            $user = User::create([
                'name' => 'Tanvir Ahmed Hera',
                'email' => $email,
            ]);
        }

        dd($user);
    }

But it looks quite weird. And also not a good habit.

But thanks for the handy method named updateOrCreate().

That's it for today. Hope you've enjoyed this tutorial. If you've any questions or face any difficulty, catch me in the comment section. Thanks for reading.