Update if exist else insert new record in laravel

Answers 1
  • UpdateOrCreate method in laravel

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

    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