Laravel中Model为空的几种判断

  1. isEmpty判断
    $user = User::where('mobile', Input::get('mobile'))->get();
    
    if (!$user->isEmpty()){
        $firstUser = $user->first()
    }
  2. Exception的处理
    try {
        $user = User::where('mobile', Input::get('mobile'))->firstOrFail();
        //Do stuff when user exists.
    } catch (ErrorException $e) {
        //Do stuff if it doesn't exist.
    }
  3. 其他
    //Use either one of the below. 
    $users = User::where('mobile', Input::get('mobile'))->get(); //Collection
    $users = User::where('mobile', Input::get('mobile'))->first(); //Model or null
    
    if (count($users)){
        //Use the collection, to get the first item use $users->first().
        //Use the model if you used ->first();
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.