How to Check if a Record Exists in Laravel Eloquent Efficiently

How to Check if a Record Exists in Laravel Eloquent Efficiently

Using Laravel, there are many occasions when you need to verify that a record exists in the database or does not exist. Rather than retrieving all of the data associated with that record, Laravel has an exists() function which allows you to efficiently check for the existence of a record within your Laravel Eloquent application.

In this blog, we’ll understand how to use exists() with a simple and practical example

Prerequisite:

  1. Composer (Latest Version)
  2. Laravel 12

Steps to Check if a Record Exists in Laravel Eloquent

  1. Create a new Laravel project
  2. Create migration and model
  3. Add dummy data
  4. Create controller
  5. Use the exists() method
  6. Add route
  7. Test the output

Step 1: Create a New Laravel Project

composer create-project laravel/laravel exists-demo

Move into the project:

cd exists-demo
php artisan serve

Step 2: Create Model and Migration

Run the following command:

php artisan make:model UserProfile -m

Now open the migration file and update it as below,

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

Run the migration:

php artisan migrate

Step  3: Add Dummy Data

Here, we use the seeder for the data entry.

Run this command:

php artisan make:seeder UserProfileSeeder

Now open:

database/seeders/UserProfileSeeder.php

and update it as below:

use App\Models\UserProfile;

public function run(): void
{
    UserProfile::create([
        'name' => 'John Doe',
        'email' => 'john@example.com',
    ]);
    UserProfile::create([
        'name' => 'Jane Smith',
        'email' => 'jane@example.com',
    ]);
}

Now run the seeder:

php artisan db:seed --class=UserProfileSeeder

Step 4: Create Controller

Now, run the following command.

php artisan make:controller UserProfileController

Step 5: Use the exists() Method

Now open the controller and add the following code:

use App\Models\UserProfile;

public function index()
{
    $userExists = UserProfile::where('email', 'john@example.com')->exists();
    if ($userExists) {
        return response()->json([
            'message' => 'User found.'
        ]);
    }
    return response()->json([
        'message' => 'User not found.'
    ]);
}

Step 6: Add Route

Open the routes/web.php file and add the following route:

use App\Http\Controllers\UserProfileController;
Route::get('/check-user', [UserProfileController::class, 'index']);

Step 7: Test the Output

After the above steps, now you can see the output at,

http://127.0.0.1:8000/check-user

After visiting the URL, you will get the output as shown below:

{
    "message": "User found."
}

If the email does not exist in the database, the response will be:

{
    "message": "User not found."
}

Conclusion:

The exists() method is a very small but useful method that comes with the Laravel Framework. Generally speaking, if you are just checking to see if a record exists or not, using exists() is the best choice for the performance of your query.

FAQ

1. What is Laravel Eloquent?

Laravel Eloquent is the built-in Object-Relational Mapping (ORM) system in the Laravel Framework, allowing developers to interact with database tables through the use of PHP models rather than writing raw SQL statements.

2. Why is checking record existence important in web applications?

Checking if a record exists serves as a way to avoid duplicate records, validate inputs by users; and to enforce business rules; therefore, making the application more reliable.

3. Which Laravel method is best for checking if a record exists?

The most efficient way to determine if a record exists in a database is by using the exists() method, which will allow you to check for the existence of a record without having to retrieve any data from your database.

Previous Article

How to Create Custom Helper Functions in Laravel 12?

Next Article

How to Integrate AdminLTE 3 in Laravel 12?

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 ✨