Answer the question
In order to leave comments, you need to log in
How are slugs formed in laravel?
It is necessary to immediately form a slug in the admin panel when entering a title. There are several such pages, because the types are different (categories, pages, posts, products, users, etc.). It seems nothing complicated, I do slugs through Str:slug. But, I don't want to write the same thing in every controller/model. Therefore, I create a separate class - slug generator. Class structure:
class SlugController extends Controller
{
public function generate($phrase, $limit = 255)
{
$slug = Str::slug($phrase);
if( strlen($slug) > $limit ) return Str::substr($slug, 0, $limit);
else return $slug;
}
public function isUniq($table, $field, $slug)
{
$result = $table->where($field, $slug)->first();
if(! $result ) return true;
return false;
}
public function generateUniqSlug($table, $phrase, $limit)
{
$slug = $this->generate($phrase, $limit);
if( $this->isUniq($table, $field, $slug) ) return $slug;
else {
for($i = 1; $i < 200; $i++) {
$newSlug = $slug . '-' . $i;
if( $this->isUniq($table, $field, $slug) ) return $newSlug;
}
}
}
}
Answer the question
In order to leave comments, you need to log in
You can validate the data that comes to the controller through custom Request classes . There you can specify the following structure:
public function rules()
{
return [
'slug' => [
'string',
'unique:posts,slug'
],
];
}
protected function prepareForValidation() :void
{
$this->merge([
'slug' => ($this->slug) ?? \Str::slug($this->title, '-')
]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question