Update if exist else insert new record in laravel

Updated at 05-Apr-2021, By samar

Update if exist else insert new record in laravel

We’ll attempt to use programming in this lesson to solve the "Update if exist else insert new record in laravel" puzzle.

  • UpdateOrCreate method in laravel

    --PATH app\Http\Controllers\<YourController>.php
    $User = User::updateOrCreate(
        ['username' => $request->username],
        ['email' => $request->email, 'password' => bcrypt($request->password)]

    Laravel provides the method updateOrCreate to insert a new record if it does not exist and update if it exists. It has two parameters, conditions and fields and these parameters should be array. It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new record after applying attributes passed in the second parameter with the merging first argument array and updates the record if the record already exists in the table.

    This code snippet creates a new user record if the user with this particular username is not exist in the table, else it update the user email and password columns value using the second argument array if the record exists in the table.

Back to code snippet queries related laravel