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