Laravel exists() method Example

saim - May 20 '21 - - Dev Community

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();
Enter fullscreen mode Exit fullscreen mode

Example 2

for search email

if (User::where('email', $request->email)->exists()) {
   //email exists in user table
}
Enter fullscreen mode Exit fullscreen mode

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.');
 }
Enter fullscreen mode Exit fullscreen mode

Read also

Laravel php artisan inspire command
Laravel clear cache without using artisan command

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .