Laravel Checking If a Record Exists

后端 未结 26 2066
礼貌的吻别
礼貌的吻别 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:17

    I think below way is the simplest way to achieving same :

        $user = User::where('email', '=', $request->input('email'))->first();
        if ($user) {
           // user doesn't exist!
        }
    
    0 讨论(0)
  • 2020-11-28 18:19

    The Easiest Way to do

        public function update(Request $request, $id)
    {
    
    
        $coupon = Coupon::where('name','=',$request->name)->first(); 
    
        if($coupon->id != $id){
            $validatedData = $request->validate([
                'discount' => 'required',   
                'name' => 'required|unique:coupons|max:255',      
            ]);
        }
    
    
        $requestData = $request->all();
        $coupon = Coupon::findOrFail($id);
        $coupon->update($requestData);
        return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
    }
    
    0 讨论(0)
  • 2020-11-28 18:19

    The efficient way to check if the record exists you must use is_null method to check against the query.

    The code below might be helpful:

    $user = User::where('email', '=', Input::get('email'));
    if(is_null($user)){
     //user does not exist...
    }else{
     //user exists...
    }
    
    0 讨论(0)
  • 2020-11-28 18:21
    $email = User::find($request->email);
    If($email->count()>0)
    <h1>Email exist, please make new email address</h1>
    endif
    
    0 讨论(0)
  • 2020-11-28 18:23

    One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.

    0 讨论(0)
  • 2020-11-28 18:25
    $user = User::where('email', request('email')->first();
    return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
    
    0 讨论(0)
提交回复
热议问题