DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Laravel exists() method Example
larainfo
larainfo

Posted on • Originally published at larainfo.com

Laravel exists() method Example

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

Top comments (1)

Collapse
 
sloan profile image
Info Comment hidden by post author - thread only accessible via permalink
Sloan

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

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.