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

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

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


当前回答

简单,舒适和易于理解的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);
        }

其他回答

if (User::where('email', 'user@email.com')->first()) {
    // It exists
} else {
    // It does not exist
}

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

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

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

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

最简单的方法

    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!');
}
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
if ($u = User::where('email', '=', $value)->first())
{
   // do something with $u
   return 'exists';
} else {
  return 'nope';
}

可以用try/catch吗

->get()仍然返回一个空数组