How to validation slug in laravel 5.4.24

2019-08-06 19:16发布

How to create unique slug in laravel and validate them ?

Here is my validation code:

$this->validate($request,[
        'company_name' => 'required|unique:admin_users,company_name,slug|max:191',
    ]);

Here is my slug code:

$db_filed->company_name = str_slug($request->company_name, '-');

Thanks.

3条回答
甜甜的少女心
2楼-- · 2019-08-06 19:36

you can create the slug inside your controller probably inside the store function like this

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楼-- · 2019-08-06 19:38

Setup a FormRequest to do the validation for the route with the rules like this:

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.

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();
}
查看更多
Summer. ? 凉城
4楼-- · 2019-08-06 19:41

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();
}
查看更多
登录 后发表回答