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 04:05
if($user->isEmpty()){
    // has no records
}

Eloquent uses collections. See the following link: https://laravel.com/docs/5.4/eloquent-collections

查看更多
够拽才男人
3楼-- · 2019-01-08 04:11
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

can be written as

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

This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.

查看更多
beautiful°
4楼-- · 2019-01-08 04:13

In your Controller

$this->validate($request, [
        'email' => 'required|unique:user|email',
    ]); 

In your View - Display Already Exist Message

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
查看更多
5楼-- · 2019-01-08 04:13

this is simple code to check email is exist or not in database


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

查看更多
别忘想泡老子
6楼-- · 2019-01-08 04:14

Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.

if ( User::find( $userId ) === null ) {

    return "user does not exist";
}
else {
    $user = User::find( $userId );

    return $user;
}

It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.

查看更多
仙女界的扛把子
7楼-- · 2019-01-08 04:18

One of the best solution is to use the firstOrNew or firstOrCreate method.

查看更多
登录 后发表回答