I'm assuming your question is asking how you can generate uri's for categories that can have an unlimited amount of children via their slugs.
How I would go about tackling something like this is by using a hierarchical data pattern within MySQL which will allow you to get a list of descendants / ancestors by performing one query. There are numerous ways to implement this, but for the purpose of this explanation I'm going to explain how to do it using the nested set pattern. More specifically, I'll be giving demonstrating how to do this using lazychaser's nested set package.
Categories Table Migration
use Kalnoy\Nestedset\NestedSet;
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
NestedSet::columns($table);
$table->timestamps();
});
The nested set columns will add _lft
, _rgt
, and parent_id
columns to your table. I would recommend you do some research on how the nested set model works in order to understand what the left and right columns are used for.
Category Model
use Kalnoy\Nestedset\NodeTrait;
class Category extends Model
{
use NodeTrait;
//
}
Now you can create a child category like so:
$parentCategory = Category::first();
$parentCategory->children()->create([
'name' => 'Example Category'
]);
This means that on a deeply nested category you can do:
$categories = Category::ancestorsAndSelf($article->category_id);
This will return all ancestors of the above category, then to get the uri you can do something like:
$uri = $categories->pluck('slug')->implode('/') . '/' . $article->slug;