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'); }
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'); }
<?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
Leave a reply