Breaking up the web.php file
Breaking up the web.php file
This is a file that can easily become very large and difficult to manage

I have just finished a program suite with many hundreds of routes. 

I do tend to used named routes and then do the work in the controller rather than the web file.

For example two of my routes are

Route::get('gallery.sort' , 'GalleryController@sort')->name('gallery.sort');
Route::post('gallery.storeSort','GalleryController@storeSort')->name('gallery.storeSort');

This type of route is not covered in the standard resource settings and if you have quite a few of these it can become very unmanageable. 

For example, I have a sub-directory under the routes directory called inc_routes, and in there is a file gallery.php which contains everything to do with routes for the gallery (obviously!).

Route::group(['prefix' => 'admin'], function ()
{
Route::get('gallery.sort','GalleryController@sort')->name('gallery.sort');
Route::post('gallery.storeSort','GalleryController@storeSort')->name('gallery.storeSort');
}

(there are other routes as well, but you get the idea).

Now telling Laravel to read this file as part of its routing is easy.

In app\Providers is a file RouteServiceProvider.php and this is read at boot and maps everything.

So we need to tell RouteServiceProvider to include this file when it is making up the routes.

You will see that two routes are mapped by default in a function map:

public function map()
{
     $this->mapApiRoutes();
     $this->mapWebRoutes();
}

So we need to tell this file to include my galleries.php file in the mapping, which is very easy.

In the RouteServiceProvider create a function:

protected function mapGalleryRoutes()
{
Route::middleware('web')             
                ->namespace($this->namespace)
               ->group(base_path('routes/inc_routes/gallery.php'));
}

and now include the map function in the list at the top of file, so it now becomes

public function map()
{
     $this->mapApiRoutes();
     $this->mapWebRoutes();
     $this->mapGalleryRoutes();
}

And that is all done. It is not a bad idea to issue the route:clear command in php artisan, but it really is that simple.

What's your reaction?

Comments

https://www.magazine.tdbcomputing.com/assets/images/user-avatar-s.jpg

0 comment

Write the first comment for this!

Facebook Conversations

Disqus Conversations