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

前端 未结 5 596
天涯浪人
天涯浪人 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:57

    get returns Collection and is rather supposed to fetch multiple rows.

    count is a generic way of checking the result:

    $user = User::where(...)->first(); // returns Model or null
    if (count($user)) // do what you want with $user
    
    // or use this:
    $user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException
    
    // count will works with a collection of course:
    $users = User::where(...)->get(); // returns Collection always (might be empty)
    if (count($users)) // do what you want with $users
    

提交回复
热议问题