Laravel 4:如何根据我的存储功能检查数据库条目是否已存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17521389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4: how do I check if a database entry already exists against my store function
提问by Josh
I'm adding posts to a database using a PostsController in Laravel 4
我正在使用 Laravel 4 中的 PostsController 将帖子添加到数据库
I use a url field in the database to determine what I use for the show post url e.g. url = example-url will mean the post's url will be example.com/example-url
我使用数据库中的 url 字段来确定我用于显示帖子 url 的内容,例如 url = example-url 将意味着帖子的 url 将是 example.com/example-url
My store function looks like this:
我的商店功能如下所示:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Post::$rules);
if($v->passes())
{
$this->post->create($input);
return Redirect::route('cms.index');
}
return Redirect::route('cms.create')
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}
What is the best way to check if the url entered already exists for another post?
检查输入的 url 是否已存在于另一篇文章中的最佳方法是什么?
Thanks!
谢谢!
回答by Andreyco
I would check it in validation step. Add this rule to your validation rules set. This rules checks for given value in database automaticaly, validation will not pass if same url is found.
我会在验证步骤中检查它。将此规则添加到您的验证规则集中。此规则自动检查数据库中的给定值,如果找到相同的 url,则验证将不会通过。
'url' => 'unique:posts'
More info about validation's Unique rule is here http://laravel.com/docs/validation#rule-unique
有关验证的唯一规则的更多信息在这里http://laravel.com/docs/validation#rule-unique
回答by Laurence
Easy - you want the Unique validation rule
简单 - 您需要唯一验证规则
Add this to your rules
将此添加到您的规则中
array('url' => 'unique:posts'),

