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

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

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


当前回答

if ($u = User::where('email', '=', $value)->first())
{
   // do something with $u
   return 'exists';
} else {
  return 'nope';
}

可以用try/catch吗

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

其他回答

如果你想在数据库中插入一条记录,而相同邮件的记录不存在,那么你可以这样做:

$user = User::updateOrCreate(
    ['email' => Input::get('email')],
    ['first_name' => 'Test', 'last_name' => 'Test']
);

updateOrCreate方法的第一个参数列出了唯一标识关联表中的记录的列,而第二个参数由要插入或更新的值组成。

你可以在这里查看文档:Laravel upserts doc

最好的解决方案之一是使用firstOrNew或firstOrCreate方法。文档中有更多关于这两者的详细信息。

拉拉维尔 5.6.26v

通过主键(电子邮件或id)查找现有记录

    $user = DB::table('users')->where('email',$email)->first();

然后

      if(!$user){
             //user is not found 
      }
      if($user){
             // user found 
      }

包括“use DB”和表名user变成复数,使用上面的查询,就像user变成users

这是一个简单的代码来检查电子邮件是否存在数据库


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

最简单的方法

    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!');
}