![Logo loader icon](https://w3codegenerator.com/img/logo-f2.png)
Update if exist else insert new record in laravel
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.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Laravel
- Get content from web URL in laravel
- Fatal error: Uncaught Error: Class "Illuminate\Foundation\Application" not found
- How to get only time from created_at in laravel
- Class 'App\Http\Controllers\User' not found
- Seed database using SQL file in Laravel
- How to get route method name in Laravel
- How to generate .env file for laravel?
- How to check column value of a record is null or not in laravel
- SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.post_id' in 'where clause
- How to create and run user seeder in laravel
- How to use bootstrap pagination in laravel 8
- How to insert ckeditor data into database in Laravel?
- Input file with max size validation in laravel
- Create a record if not exist in laravel
- Ignore Records where a field has NULL value in Laravel
- How to insert value to additional columns in pivot table in laravel
- If condition in foreach loop in laravel
- Get ids in array from users table
- Best code example for create order in Laravel for ecommerce
- How to display user profile after login in laravel
- Call to undefined method Illuminate\Support\Facades\Request::all()
- Run artisan command to generate key in laravel
- Get the products list ordered by a user
- Cast Array to an Object in Controller and then pass to view in laravel
- How to get images from AWS s3 and display in Laravel blade