How to implement categories (including nested categories) in the MVC pattern?

Development | Programming languages
How to implement a url with categories such as 

If the router is configured for http://site.com/class/method we also need nested categories, like http://site.com/category/subcategory/product.html
No attachments

The most obvious option is to create a parent parent_id relationship through an attribute and relationship parent.

class Category extends Model
    public function parent()
        return $this->belongsTo(self::class);

Also, our model has an attribute slug- a stub, which reflects the section in the URL. It can be generated from the name, or manually specified by the user. Most importantly, the stub must pass the validation rule alphadash(that is, consist of letters, numbers and signs -, _), and also be unique within the parent section. For the latter, it is enough to create a unique index in the database (parent_id, slug).

To get a link to a section, you need to pull all of his parents in sequence. The URL generation function looks something like this:

public function getUrl()
    $url = $this->slug;

    $category = $this;

    while ($category = $category->parent) {
        $url = $category->slug.'/'.$url;

    return 'catalog/'.$url;

$router->get('catalog/{category}', ...);

Feed the browser a link http://example.com/catalog/category. The route will work. Now the following link: http://example.com/catalog/category/sub-category. The route will no longer work, because backslash is a parameter delimiter. Hmm, then add another parameter and make it optional:

$router->get('catalog/{category}/{subcategory?}', ...);

This route will already work, but if you add another subsection to the URL, then nothing will work. And the problem is that the number of such subsections is not limited.

Further, in order to get the necessary section from the database, you must first find the section with the identifier category, then, if specified, the subsection subcategory, etc. All this causes inconvenience and loads the server harder; the number of requests is proportional to the number of subsections.

on January 12th, 2020 (6:22 pm)
All coments
This job has not been commented yet.