如何在laravel中创建独特的slug并验证它们?
这是我的验证码:
$this->validate($request,[
'company_name' => 'required|unique:admin_users,company_name,slug|max:191',
]);
这是我的slug代码:
$db_filed->company_name = str_slug($request->company_name, '-');
感谢。
答案 0 :(得分:2)
设置FormRequest以使用如下规则对路由进行验证:
https://laravel.com/docs/5.4/validation#form-request-validation
slice
或者您需要在将slug分配给公司名称之前创建slug。
https://laravel.com/docs/5.4/validation#manually-creating-validators
public function rules()
{
return [
'company_name' => 'required|unique:admin_users,company_name,slug|max:191'
];
}
答案 1 :(得分:1)
我尝试这种方式,现在就开始了,
这是代码形式:
<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>
这是控制器代码:
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();
}
答案 2 :(得分:0)
你可以在你的控制器里面创建一个slug,可能就像这个
那样在商店里面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);
}
答案 3 :(得分:0)
您可以在其中创建自定义规则来实现此目的。这样的东西应该就足够了:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Str;
class Slug implements Rule
{
public function passes($attribute, $value): bool
{
$validSlug = (string) Str::of($value)->slug('-');
return $value === $validSlug;
}
public function message(): string
{
return 'The :attribute must be slug formatted.';
}
}