How to check record exists or not in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today, i will show you a example of laravel how to check if record exists in database. Here We will look at an example of laravel check if record not exists. Now in this post i will give you a simple example of laravel check if record exists in table. Let’s start discuss about laravel check if record exists in database.

So, let’s start and follow the few step to create an example of laravel check if record not exists.

If you are new in laravel 8 version and you want to determine the email is exist or not then you can do it very easily. IF we did use code php then we have to write a long code and check but laravel provide us it’s own query builder so it is pretty simple and also easy. we can see the following example of how i check row is exists or not:

Example:
$user = User::where('email',Input::get('email'))->first();
if (is_null($user)) {
   print_r("email is exists");
}
   print_r("email is not exists");

exists() Example:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $isExist = User::select("*")
                        ->where("email", "[email protected]")
                        ->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\Models\User;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $isExist = User::select("*")
                        ->where("email", "[email protected]")
                        ->doesntExist();
  
        if ($isExist) {
            dd('Record is not available.');
        }else{
            dd('Record is available.');
        }
  
    }
}

Output:

Record is not available.

Read Also : How to convert Object into Array in PHP?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →