Laravel Checking If a Record Exists

后端 未结 26 2067
礼貌的吻别
礼貌的吻别 2020-11-28 17:50

I am new to Laravel. Please excuse the newbie question but how do I find if a record exists?

$user = User::where(\'em         


        
相关标签:
26条回答
  • 2020-11-28 18:14
    if($user->isEmpty()){
        // has no records
    }
    

    Eloquent uses collections. See the following link: https://laravel.com/docs/5.4/eloquent-collections

    0 讨论(0)
  • 2020-11-28 18:14
    if (User::where('email', 'user@email.com')->first()) {
        // It exists
    } else {
        // It does not exist
    }
    

    Use first(), not count() if you only need to check for existence.

    first() is faster because it checks for a single match whereas count() counts all matches.

    0 讨论(0)
  • 2020-11-28 18:14

    Laravel 5.6.26v

    to find the existing record through primary key ( email or id )

        $user = DB::table('users')->where('email',$email)->first();
    

    then

          if(!$user){
                 //user is not found 
          }
          if($user){
                 // user found 
          }
    

    include " use DB " and table name user become plural using the above query like user to users

    0 讨论(0)
  • 2020-11-28 18:15

    It's simple to get to know if there are any records or not

    $user = User::where('email', '=', Input::get('email'))->get();
    if(count($user) > 0)
    {
    echo "There is data";
    }
    else
    echo "No data";
    
    0 讨论(0)
  • 2020-11-28 18:17

    It depends if you want to work with the user afterwards or only check if one exists.

    If you want to use the user object if it exists:

    $user = User::where('email', '=', Input::get('email'))->first();
    if ($user === null) {
       // user doesn't exist
    }
    

    And if you only want to check

    if (User::where('email', '=', Input::get('email'))->count() > 0) {
       // user found
    }
    

    Or even nicer

    if (User::where('email', '=', Input::get('email'))->exists()) {
       // user found
    }
    
    0 讨论(0)
  • 2020-11-28 18:17

    This will check if requested email exist in the user table:

    if (User::where('email', $request->email)->exists()) {
       //email exists in user table
    }
    
    0 讨论(0)
提交回复
热议问题