How to Create a User with Laravel’s firstOrCreate Method?

How to Create a User with Laravel’s firstOrCreate Method

In this article, we will demonstrate how to use Laravel’s firstOrCreate method to easily retrieve or create records in the database in a clean and efficient way.

The firstOrCreate method is utilized to attempt to locate a record in the database that contains the given attributes. If it is found, the record is returned. If it is not found, a new record will be created with the included attributes.

This method is beneficial for preventing duplicate entries from occuring while keeping the data consistent.   

Laravel Development Services

Prerequirements:

1. Composer (latest Version)

2. Laravel version 12

Steps to Create a User with Laravel’s firstOrCreate Method:

Step 1: Create a New Laravel 12 Project

composer create-project laravel/laravel:^12.0 db-demo
cd db-demo

Step 2: Set Up the Database & User Model

php artisan make:model User -m

Now, open the migration file and update it:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});

Run the migration:

php artisan migrate

Step 3: Create a Controller for logic

php artisan make:controller UserController

Now open app/Http/Controllers/UserController.php and update it:

class UserController extends Controller
{
    public function storeOrFetchUser()
    {
        $user = User::firstOrCreate(
            ['email' => 'magecomp@gmail.com'], 
            ['name' => 'Magecomp']     
        );
        return response()->json([
            'message' => $user->wasRecentlyCreated ? 'User was created.' : 'User already exists.',
              'data' => $user,
        ]);
    }
}

Step 4: Define the Route

Route::get('/create-user', [UserController::class, 'storeOrFetchUser']);

Step 5: Test it in Browser

php artisan serve

Then open your browser and visit:

http://localhost:8000/create-user 

Output:

You should see a JSON response:

{
  "message": "User was created.",
  "data": {
    "id": 1,
    "name": "Magecomp",
    "email": "magecomp@gmail.com",
    ...
  }
}

Conclusion

Laravel’s firstOrCreate method makes the database interaction a single call instead of having to do a lookup and an insert in a couple of steps. 

If you have any queries, just post a comment.

Hire Laravel Expert Now

FAQ

  1. What is the firstOrCreate method in Laravel?

firstOrCreate in Laravel is an Eloquent method used to check if there is a record with the given attributes. If it is found, that record is returned; if not, a new record is created based on the given attributes.

  1. Can I use firstOrCreate to update a record if it already exists?

No, firstOrCreate can look up and create a record, but will not update one if found. You can use the method called updateOrCreate.

Previous Article

How to Create Automatic Discounts in Shopify Remix Using GraphQL?

Next Article

Magento 2: How to Extend Tailwind CSS with Custom Classes in Hyvä Theme

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨