如何在 Laravel 5.4.24 中验证 slug
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44601469/
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
How to validation slug in laravel 5.4.24
提问by MD Iyasin Arafat
How to create unique slug in laravel and validate them ?
如何在 Laravel 中创建独特的 slug 并验证它们?
Here is my validation code:
这是我的验证代码:
$this->validate($request,[
'company_name' => 'required|unique:admin_users,company_name,slug|max:191',
]);
Here is my slug code:
这是我的 slug 代码:
$db_filed->company_name = str_slug($request->company_name, '-');
Thanks.
谢谢。
回答by
Setup a FormRequest to do the validation for the route with the rules like this:
设置一个 FormRequest 以使用如下规则对路由进行验证:
https://laravel.com/docs/5.4/validation#form-request-validation
https://laravel.com/docs/5.4/validation#form-request-validation
public function rules()
{
return [
'company_name' => 'required|unique:admin_users,company_name,slug|max:191'
];
}
Or you need to create the slug before assigning it to the company name.
或者您需要在将其分配给公司名称之前创建 slug。
https://laravel.com/docs/5.4/validation#manually-creating-validators
https://laravel.com/docs/5.4/validation#manually-creating-validators
$slug = str_slug($request->company_name, '-');
$validator = Validator::make(['company_name' => $slug], [
'company_name' => 'required|unique:admin_users,company_name,slug|max:191'
]);
if (!$validator->fails()) {
$db_filed->company_name = $slug;
$db_filled->save();
}
回答by MD Iyasin Arafat
I'm trying this way and now it's work,
我正在尝试这种方式,现在它起作用了,
Here is code form:
这是代码形式:
<div class="form-group">
<input type="text" class="form-control" placeholder="Company Name" name="company_name" value="{{ ucwords(str_replace('-',' ',old('company_name'))) }}" required>
</div>
Here is controller code:
这是控制器代码:
public function store(Request $request)
{
$request['company_name'] = str_slug($request->company_name, '-');
$this->validate($request,[
'company_name' => "required|unique:admin_users,company_name|max:191",
]);
$db_filed = new AdminUser;
$db_filed->company_name = $request->company_name;
$db_filed->save();
}
回答by gbenga wale
you can create the slug inside your controller probably inside the store function like this
你可以在你的控制器中创建 slug 可能在 store 函数中这样
public function store(CompanyNameRequest $request)
{
$slug = uniqid();
$ticket = new CompaanyName(array(
'title' => $request->get('title'),
'content' => $request->get('content'),
'slug' => $slug
));
$ticket->save();
return redirect('/contact')->with('status', 'Your order is been proccess! Its unique id is: '.$slug);
}