Eloquent ->first() if ->exists()

前端 未结 5 597
天涯浪人
天涯浪人 2020-12-23 09:08

I want to get the first row in table where condition matches:

User::where(\'mobile\', Input::get(\'mobile\'))->first()

It works well, bu

5条回答
  •  一整个雨季
    2020-12-23 09:50

    Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.

    The correct way to user first() and check for a result:

    $user = User::where('mobile', Input::get('mobile'))->first(); // model or null
    if (!$user) {
       // Do stuff if it doesn't exist.
    }
    

    Other techniques (not recommended, unnecessary overhead):

    $user = User::where('mobile', Input::get('mobile'))->get();
    
    if (!$user->isEmpty()){
        $firstUser = $user->first()
    }
    

    or

    try {
        $user = User::where('mobile', Input::get('mobile'))->firstOrFail();
        // Do stuff when user exists.
    } catch (ErrorException $e) {
        // Do stuff if it doesn't exist.
    }
    

    or

    // Use either one of the below. 
    $users = User::where('mobile', Input::get('mobile'))->get(); //Collection
    
    if (count($users)){
        // Use the collection, to get the first item use $users->first().
        // Use the model if you used ->first();
    }
    

    Each one is a different way to get your required result.

提交回复
热议问题