DEV Community

loading...
Cover image for Laravel exists() method Example

Laravel exists() method Example

larainfo
Full Stack Developer | Laravel | Livewire | Vue Js Nodejs, tailwind css
Originally published at larainfo.com ・1 min read

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

Discussion (1)

Some comments have been hidden by the post's author - find out more