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

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

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


当前回答

我认为下面的方法是达到同样目的的最简单的方法:

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user exist!
    }else{
       // user does not exist
    }

其他回答

这是一个简单的代码来检查电子邮件是否存在数据库


    $data = $request->all();
    $user = DB::table('User')->pluck('email')->toArray();
    if(in_array($user,$data['email']))
    {
    echo 'existed email';
    }

要知道是否有记录是很简单的

$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";
if (User::where('email', 'user@email.com')->first()) {
    // It exists
} else {
    // It does not exist
}

如果只需要检查是否存在,请使用first(),而不要使用count()。

First()更快,因为它检查单个匹配,而count()计数所有匹配。

这将检查用户表中是否存在所请求的电子邮件:

if (User::where('email', $request->email)->exists()) {
   //email exists in user table
}

简单,舒适和易于理解的Validator

class CustomerController extends Controller
{
    public function register(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:customers',
            'phone' => 'required|string|max:255|unique:customers',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response(['errors' => $validator->errors()->all()], 422);
        }