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

时间:2014-07-02 12:39:57

标签: php laravel eloquent

我想得到条件匹配的表中的第一行:

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

效果很好,但如果条件不匹配,则抛出异常:

ErrorException
Trying to get property of non-object

目前我这样解决:

if (User::where('mobile', Input::get('mobile'))->exists()) {
    $user = User::where('mobile', Input::get('mobile'))->first()
}

我可以不运行两个查询吗?

5 个答案:

答案 0 :(得分:102)

注意:first()方法不会抛出原始问题中描述的异常。如果您遇到此类异常,则代码中会出现其他错误。

用户first()的正确方法并检查结果:

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

其他技术(不推荐,不必要的开销):

$user = User::where('mobile', Input::get('mobile'))->get();

if (!$user->isEmpty()){
    $firstUser = $user->first()
}

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

// 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();
}

每种方法都是获得所需结果的不同方式。

答案 1 :(得分:1)

(ps - 我无法发表评论)我认为你最好的选择就像你做过的那样,或类似于:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

哦,而且:count()代替exists,但这可能是在get之后使用的内容。

答案 2 :(得分:1)

get返回Collection,而应该提取多行。

count是检查结果的通用方法:

$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

答案 3 :(得分:0)

以一种简单的方式尝试即可运行

$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";

答案 4 :(得分:-1)

答案已被接受,但在这些情况下,我认为更优雅的解决方案是使用错误处理。

    try {
        $user = User::where('mobile', Input::get('mobile'))->first();
    } catch (ErrorException $e) {
        // Do stuff here that you need to do if it doesn't exist.
        return View::make('some.view')->with('msg', $e->getMessage());
    }