
Create a record if not exist in laravel
-
Laravel firstOrCreate method to create a record if it not already exist in the table
--PATH app\Http\Controllers\<YourController>.phpPost::firstOrCreate( ['slug'=> $request->slug], ['title' => $request->title, 'body' => $request->body] );
1firstOrCreate method is used to create a record if it does not already exist in the table in laravel. It has two parameters, conditions and fields and these parameters should be an 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 parameters including first parameter field and values.
This code snippet will create a new post record including title, body and slug fields in the post table if the record is not already exist with this particular slug.
-
Create a new record if not exist in laravel using create method
--PATH app\Http\Controllers\<YourController>.php$user = User::where('username', $request->username)->first(); if(!$user){ $user = User::create([ 'email' => $request->email, 'username' => $request->username, 'password' => bcrypt($request->password) ]); }
0This code snippet helps you to find the record if any already exists with this particular username and check that if the user with this particular username is not already exist then it creates a new user using the create() method.
Random Code Snippet Queries: Laravel
- Get only 10 records from table in laravel
- How to display 1 day ago in comments in laravel view
- How to generate .env file for laravel?
- Pass variable from blade to controller Laravel
- How to get all route list
- How to pass variable from controller to model in Laravel
- Return redirect laravel not working
- Pagination in laravel
- Laravel form request validation
- Array to string conversion laravel blade
- How to get specific columns using with method in laravel Eloquent relationship
- Call to a member function pluck() on null
- How to get query string value in laravel
- Composer\Exception\NoSslException
- Illuminate\Database\QueryException could not find driver
- Use withCount() to Calculate Child Relationship Records
- Create model with migration and seeder
- Extra Filter Query on Relationships in Laravel
- Credit card validation in laravel
- How to add columns in existing table using migration in laravel
- How to check column value of a record is null or not in laravel
- Get products with number of orders in Laravel
- Rendering HTML from database table to view in Laravel
- Laravel 9 pagination with search filter
- How to display a specific word from a string in laravel