Laravel Checking If a Record Exists

2019-01-08 03:32发布

I am new to Laravel. Please excuse the newbie question but how do I find if a record exists?

<?php

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

What can I do here to see if $user has a record?

14条回答
欢心
2楼-- · 2019-01-08 03:58

Shortest working options:

// 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();
查看更多
女痞
3楼-- · 2019-01-08 04:00

It depends if you want to work with the user afterwards or only check if one exists.

If you want to use the user object if it exists:

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

And if you only want to check

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

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}
查看更多
唯我独甜
4楼-- · 2019-01-08 04:01

Laravel 5.6.26v

to find the existing record through primary key ( email or id )

    $user = DB::table('users')->where('email',$email)->first();

then

      if(!$user){
             //user is not found 
      }
      if($user){
             // user found 
      }

include " use DB " and table name user become plural using the above query like user to users

查看更多
成全新的幸福
5楼-- · 2019-01-08 04:03

It's simple to get to know if there are any records or not

$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
查看更多
Summer. ? 凉城
6楼-- · 2019-01-08 04:03

you can use laravel validation .

But this code is also good:

$user = User::where('email',  $request->input('email'))->count();

if($user > 0)
{
   echo "There is data";
}
else
   echo "No data";
查看更多
Explosion°爆炸
7楼-- · 2019-01-08 04:03

This will check if particular email address exist in the table:

if (isset(User::where('email', Input::get('email'))->value('email')))
{
    // Input::get('email') exist in the table 
}
查看更多
登录 后发表回答