我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$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()仍然返回一个空数组
其他回答
if($user->isEmpty()){
// has no records
}
Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections
这取决于您是想在之后使用用户,还是只检查是否存在一个用户。
如果用户对象存在,你想使用它:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
如果你只是想检查一下
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
或者更好
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
如果你想在数据库中插入一条记录,而相同邮件的记录不存在,那么你可以这样做:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
updateOrCreate方法的第一个参数列出了唯一标识关联表中的记录的列,而第二个参数由要插入或更新的值组成。
你可以在这里查看文档:Laravel upserts doc
这有点晚了,但它可能会帮助那些试图使用User::find()->exists()来记录存在的人,因为Laravel为find()和where()方法显示了不同的行为。假设电子邮件是你的主键,让我们来看看这种情况。
$result = User::find($email)->exists();
如果存在该电子邮件的用户记录,则返回true。然而,令人困惑的是,如果不存在该电子邮件的用户,那么它将抛出一个错误。即
Call to a member function exists() on null.
但是where()的情况是不同的。
$result = User::where("email", $email)->exists();
如果记录存在,上面的子句将返回true,如果记录不存在则返回false。因此,总是尝试使用where()来表示记录是否存在,而不使用find()来避免NULL错误。
最简单的方法
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!');
}