Laravel Checking If a Record Exists

后端 未结 26 2083
礼貌的吻别
礼貌的吻别 2020-11-28 17:50

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

$user = User::where(\'em         


        
相关标签:
26条回答
  • 2020-11-28 17:59
    if (User::where('email', Input::get('email'))->exists()) {
        // exists
    }
    
    0 讨论(0)
  • 2020-11-28 18:00
    if ($u = User::where('email', '=', $value)->first())
    {
       // do something with $u
       return 'exists';
    } else {
      return 'nope';
    }
    

    would work with try/catch

    ->get() would still return an empty array

    0 讨论(0)
  • 2020-11-28 18:00

    Created below method (for myself) to check if the given record id exists on Db table or not.

    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);
    

    Home It helps!

    0 讨论(0)
  • 2020-11-28 18:01

    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";
    
    0 讨论(0)
  • 2020-11-28 18:05

    In laravel eloquent, has default exists() method, refer followed example.

    if(User::where('id', $user_id )->exists()){ // your code... }

    0 讨论(0)
  • 2020-11-28 18:07

    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
    
    0 讨论(0)
提交回复
热议问题