如何在 laravel 5.4.24 中验证 slug

How to validation slug in laravel 5.4.24

如何在 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, '-');

谢谢。

设置一个 FormRequest 以使用如下规则对路由进行验证:

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'
    ];
}

或者您需要先创建 slug,然后再将其分配给公司名称。

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();
}

我正在尝试这种方式,现在可以了,

代码格式如下:

 <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();
}

你可以像这样在你的控制器中创建 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);

}

您可以在中创建自定义规则来实现此目的。这样的东西应该足够了:

<?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.';
    }
}