in this short tutorial we will see how to use laravel exists() method, we will use exists() for checking records
exists contains true if the model taken from database
let see some example
Example 1
// For Kids
$kids = User::where('age', '<', 18)->exists();
// For men
$mens = User::where('age', '>=', 18)->exists();
Example 2
for search email
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
Example 3
$posts = Post::where('user_id', Auth::id());
//Check if posts exists
if ($posts->exists()) {
//Get all the posts by user
$userPosts = $posts->get();
} else {
return redirect()->back()->withError('No post found.');
}
Read also
Laravel php artisan inspire command
Laravel clear cache without using artisan command
Top comments (1)
Hi there, we encourage authors to share their entire posts here on DEV, rather than mostly pointing to an external link. Doing so helps ensure that readers don’t have to jump around to too many different pages, and it helps focus the conversation right here in the comments section.
If you choose to do so, you also have the option to add a canonical URL directly to your post.
Some comments have been hidden by the post's author - find out more