dimanche 11 septembre 2016

nested categories routing in Laravel 5.1

I have catalog with 4 nested categoies levels. Each subcategory could have items and/or nested categories. As long as I walking on the subcategory pages everything is OK. But when I try to go to item page, then I get ModelNotFoundException, because Laravel cannot understand that it is not category anymore.

-Catalog     (instance of Category model level 1)
--Cat1       (instance of Category model level 2)
--Product1   (instance of Item model)
--Product2
--Product3
...
--Cat2       (instance of Category model level 2)
---Product1  (instance of Item model)
---Product2
---Product3
...
---Cat3      (instance of Category model level 3)
----Product1 (instance of Item model)
----Product2
----Product3
...
----Cat3      (instance of Category model level 4)
-----Product1 (instance of Item model)
-----Product2
-----Product3

routes.php

    Route::get('catalog', ['as' => 'catalog.index', 'uses' => 'CatalogController@getIndex']);
    Route::get('catalog/{category}', ['as' => 'catalog.cat', 'uses' => 'CatalogController@getCategory'])->where(['category' => '.*']);
    // {category} could be equal to 'doors' or 'doors/glass' or unfinite number of sublevels
    Route::get('catalog/{category}/{item}', ['as' => 'catalog.item', 'uses' => 'CatalogController@getItem']);
    // this route is never working, because laravel always render {category}/{item} as {category} 

RouteServiceProvider.php

public function boot(Router $router)
{
    parent::boot($router);

    Route::bind('category', function($cat) {
        $bread = explode("/", substr($cat, 0));
        $sef = array_pop($bread);
        return Category::whereSef($sef)->firstOrFail();
    });


}

Every category in database has sef which is not equal to path
Example: url = http://ift.tt/2cmQx0j
Sef for glass = glass (not catalog/doors/glass)
That is why I use explode in RouteServiceProvider to catch sef of element after last slash.

The problem is when I have url for the item then I have following error

ModelNotFoundException in Builder.php line 223: No query results for model [App\Category].

This happens because in URL http://ift.tt/2c7ZEov laravel still looking door1 in Category model not in Item model. But I don't know what to do to explain laravel that $category is finished now.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire