我刚来拉拉维尔。如何查找是否存在记录?

$user = User::where('email', '=', Input::get('email'));

我能做什么来查看$user是否有记录?


当前回答

最好的解决方案之一是使用firstOrNew或firstOrCreate方法。文档中有更多关于这两者的详细信息。

其他回答

最短工作选项:

// if you need to do something with the user 
if ($user = User::whereEmail(Input::get('email'))->first()) {

    // ...

}

// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();

这取决于您是想在之后使用用户,还是只检查是否存在一个用户。

如果用户对象存在,你想使用它:

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

如果你只是想检查一下

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

或者更好

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

创建下面的方法(为自己),以检查给定的记录id是否存在于Db表中。

private function isModelRecordExist($model, $recordId)
{
    if (!$recordId) return false;

    $count = $model->where(['id' => $recordId])->count();

    return $count ? true : false;
}

// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);

有帮助!

你已经看到了很多解决方案,但是神奇的检查语法可以是这样的,

$model = App\Flight::findOrFail(1);

$model = App\Flight::where('legs', '>', 100)->firstOrFail();

当没有找到任何相关模型时,它会自动引发一个响应404的异常,有时你可能希望在没有找到模型时抛出一个异常。这在路由或控制器中特别有用。fingernail和firstOrFail方法将检索查询的第一个结果;但是,如果没有找到结果,则会抛出一个Illuminate\Database\Eloquent\ModelNotFoundException异常。

裁判:https://laravel.com/docs/5.8/eloquent # retrieving-single-models

$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');