Home / Snippets / Ways to Check If Record Exists In Laravel
Ways to Check If Record Exists In Laravel cover

Ways to Check If Record Exists In Laravel

1.7K

3 years ago

0 comments

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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this