Laravel Checking If a Record Exists

后端 未结 26 2363
礼貌的吻别
礼貌的吻别 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 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!

提交回复
热议问题