Laravel Eloquent exists() and doesntExist() Example

By Hardik Savani April 16, 2024 Category : Laravel

This tutorial shows you laravel exists query builder. i explained simply about laravel doesntExist example. you will learn how to check if record exists in laravel. i explained simply about laravel check if record exists in database.

You can check if records is exists or not in database with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 app.

Laravel added two more eloquent methods exists() and doesntExist() for check if record exists in database table or not. so i will give you very simple example so you don't need to use first() and then check is null or not. we will use direct exists() and doesntExist() that will help you to determine if exist or not.

exists() and doesntExist() methods return true or false value so you have to just put in your condition.

Let's see bellow example:

exists() Example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$isExist = User::select("*")

->where("email", "yemmerich@example.net")

->exists();

if ($isExist) {

dd('Record is available.');

}else{

dd('Record is not available.');

}

}

}

Output:

Record is available.

doesntExist() Example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$isExist = User::select("*")

->where("email", "yemmerich@example.net")

->doesntExist();

if ($isExist) {

dd('Record is not available.');

}else{

dd('Record is available.');

}

}

}

Output:

Record is not available.

I hope it can help you...

Tags :
Shares