如何在Laravel中使用唯一验证? [英] How to use unique validation in laravel?
问题描述
我有评论表:
我的Comment控制器,它从表单中获取值并将其验证并将其存储在数据库中.
My Comment controller where its taking values from form and validating it and storing it in database.
public function store(Request $request, $product_id)
{
$this->validate($request, array(
'name' => 'required',
'email'=> 'required|email|unique:comments,product_id',
'comment' => 'required',
'rating' => 'required|integer'
));
$product = Product::find($product_id);
$comment = new Comment();
$comment->name = $request->name;
$comment->email = $request->email;
$comment->comment = $request->comment;
$comment->rating = $request->rating;
$comment->product()->associate($product);
$comment->save();
Session::flash('success','Comment was added');
return redirect()->route('product.show',[$product->id]);
}
我正在尝试验证,仅允许唯一的电子邮件ID对每个product_id进行评论,也就是说,如果用户已经对product_id 1进行了评论,则不允许同一用户再次对该ID进行评论.
我尝试了
'email'=> 'required|email|unique:comments,product_id'
但是正如您所见,为相同的product_id输入了相同的电子邮件ID数据.
But as u can see about same email id data was entered for same product_id.
用户可以在n个product_id页面上发表评论,但是一旦对该ID发表评论就无法再次发表评论.
A user can comment on n number of product_id page but cannot comment again once he has commented on that id.
是否可以验证是否已针对特定product_id在数据库中输入了电子邮件数据,然后不允许同一封电子邮件提交表单.
如果有不同的product_id,则可以输入电子邮件.
If different product_id then email can enter.
谢谢.
推荐答案
在控制台中写入
php artisan make:provider ValidationServiceProvider
然后用
namespace App\Providers;
use Validator;
use App\Comment;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
Validator::extend('unique_email_comment', function($attribute, $value, $parameters, $validator) {
return !Comment::where('email', $value)->where('product_id', $parameters[0])->exists();
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register() {
//
}
}
注意:-请确保将模型App\Comment
替换为用于注释系统的模式的命名空间.
Note :- Please ensure the Model App\Comment
is replaced with the namespace of the modal you use for your comments system.
现在将其添加到config/app.php
中的提供者,如
Now add it to providers in config/app.php
like
App\Providers\ValidationServiceProvider::class,
现在,您可以通过以下方式验证行的存在:
Now, you can validate the existence of the row by:
'email' => 'unique_email_comment:' . $productId;
// or
// 'email' => 'unique_email_comment:' . request()->get('product_id');
您还可以添加这样的自定义消息
You can also add a custom message like this
return [
'email.unique_email_comment' => 'A comment has already been made for this product with the email provided';
]
请注意,我还没有测试代码,但是如果所有数据都正确传递并且所有名称空间都正确使用,这应该可以工作.
这篇关于如何在Laravel中使用唯一验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!