Home > Software engineering >  How to use old Laravel routing style in Laravel 8
How to use old Laravel routing style in Laravel 8

Time:12-26

I just installed Laravel 8 and in this version, I have to type my routes like this:

Route::get('/admin/panel', [App\Http\Controllers\Admin\PanelController::class, 'index']);

But I got used to Laravel 5 routes which looked like this:

Route::namespace('Admin')->prefix('admin')->group(function () {
    Route::get('/panel', 'Admin/PanelController@index');
});

So how can I use this Laravel 5 routing inside Laravel 8 version?

CodePudding user response:

You can still use it to some extend (e.g. grouping and prefixing a route) but because you're using a FQCN the namespace is redundant. The major advantage using the "new" routing over of the "old" one is refactoring. When you move or rename your controller with an IDE that supports refactoring like PhpStorm you wouldn't need to manually change the name and group namespace of your controller.

In Laravel 5 you were able to use this route notation too but it wasn't outlined in the documentation.

To achieve a similar feeling, import the namespace and use just your class names and get rid of the namespace-group in the definition.

use App\Http\Controllers\Admin\PanelController;

Route::prefix('admin')->group(function () {
    Route::get('panel', [PanelController::class, 'index']);
});

If you just cannot live with the new way of defining routes, uncomment the $namespace property in app/Providers/RouteServiceProvider.php and you're back to the old way.

CodePudding user response:

If you're wanting to continue using the "older" way of defining a route (i.e. Controller@action) then you can do so but you need to alter the RouteServiceProvider to include the App\Http\Controllers namespace.

This is pretty straight forward and is with the more recent versions of Laravel 8 a simple case of uncommenting the following line:

protected $namespace = 'App\\Http\\Controllers';

If the version of Laravel 8 you're using doesn't have this line in the RouteServiceProvider file, you could upgrade your Laravel version or manually add it. If you manually add the line, you will also need to update the Route definitions in the boot method to use the $namespace property. Again, this is very straight forward, just add the following to the web and api definitions:

->namespace($this->namespace)

So for example:

Route::middleware('web')
    ->namespace($this->namespace)
    ->group(base_path('routes/web.php'));

Then you should be good to go.

  • Related