Posts Learn Components Snippets Categories Tags Tools About
/

Ways to Check If Record Exists In Laravel

Learn the ways to check if a record exists in the Laravel application and perform an action based on the availability of the records.

Created on Oct 01, 2021

1685 views

There are several ways to check if a record exists in Laravel and you will get to know all of the ways below in this snippet.

Check Record Using Exists


The first way to check if a record exists is using the "exists()" method available to the Query Builder class, using this method you will get a boolean value whether a record exists or not.
<?php

if (Post::where('id', 1)->exists()) {
    dd('this post is exists');
} else {
    dd('this post is NOT exists');
}

Check Record Using First


The second way to check whether a record exists or not is to use the "first()" which will retrieve the first instance and then check it with the "isset" function to see if there's any value or not.
<?php

$post = Post::where('id', 1)->first();

if (isset($post)) {
    dd('this post is exists');
} else {
    dd('this post is NOT exists');
}

Check Record Using isNotEmpty


The third way is to check using "isNotEmpty()" method and this method will check against the collection.
<?php

$posts = Post::where('id', '>', 100)->get();

if ($posts->isNotEmpty()) {
    dd('posts exists');
} else {
    dd('posts NOT exists');
}
The inverse of this method is to use the "isEmpty()".

Check Record Using count


The fourth way is to check using the "count()" function and this will count the total number of collections of the record.
<?php

$posts = Post::where('id', '>', 100)->get();

if (count($posts)) {
    dd('posts exists');
} else {
    dd('posts NOT exists');
}
If you prefer to count the number of "posts" by chaining the method then it will be as follows.
<?php

$posts->count();

Use Cases


The use cases of these checking is to ensure that there are records before performing some additional code logic. Below is the code example of checking if posts exist before looping through the data.
@if ($posts->isNotEmpty()) {
    @foreach ($posts as $post)
        {{-- your code logic here --}}
    @endforeach
@endif

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Ways to Check If Record Exists In Laravel

)