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
- Skip first n record and display rest records in laravel view
- How to display 1 day ago in comments in laravel view
- Call to undefined method App\Models\User::follow()
- How to generate .env file for laravel?
- Check if Relationship Method Exists in Laravel
- Laravel recursive function in controller
- Display first n record from collection in laravel view
- Run artisan command to generate key in laravel
- Route group with URI prefix using middleware and route name prefixes
- Non-static method App\Http\Helper::myFunction() should not be called statically
- Comment .env file in laravel
- Attempt to read property "avatar" on null in Laravel
- How to send email in laravel
- How to get specific columns using with method in laravel Eloquent relationship
- How to add foreign key in laravel using migration
- How to get CSRF token in laravel controller
- Convert multidimensional array to single array in Laravel
- Define variable and use in Laravel controller method
- How to avoid duplicate entries in pivot table in Laravel
- Insert data with form validation using ajax in laravel
- How to pass external link in laravel blade to anchor tag
- How to remove P tag from CkEditor in Laravel?
- How to return error message from controller to view in laravel
- How to get route name on visit URL in laravel
- How to insert value to additional columns in pivot table in laravel