
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
- How to get count of all records created at yesterday
- Drop foreign key column in Laravel using migration
- SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel8.projects' doesn't exist
- How to upload files to amazon s3 bucket using Laravel
- Array to string conversion laravel blade
- Insert Comma Separated Values in laravel
- Get last record from table in laravel
- Eager loading dynamically in laravel
- Order by multiple columns in Laravel
- Retrieve count of nested relationship data in Laravel
- Ignore Records where a field has NULL value in Laravel
- Recursive function example code PHP Laravel
- Run artisan command to generate key in laravel
- Route [password.request] not defined
- How to check email is valid or not in Laravel
- How to get route name on visit URL in laravel
- Insert values in pivot table dynamically in laravel
- External link not working in laravel blade
- Laravel 9 pagination with search filter
- How to get records in random order in laravel
- Update email with unique validation in laravel
- Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request
- How to create and run user seeder in laravel
- How to get path from current URL in Laravel
- How to pass data to partial view file in laravel