Laravel How to

Laravel 8 : Routing Change You Need to Know

Released on September 8th 2020, Laravel 8 again have some changes might be break you current laravel project. What is it ? Routing.

Let’s say we have index function in controller called NewsController.php. And on the routing file, we set routing name with the function name like this

routes/web.php

Route::get('/', 'NewsController@index');

App\Http\Controllers\NewsController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index() {
        return view('welcome');
    }
}

And when we try to run it will showing Error like this

Illuminate\Contracts\Container\BindingResolutionException
Target class [NewsController] does not exist.

Firstly i guess maybe i was typo or something. But is not. Then figure out that we can not set routing like that again on Laravel 8 at least by default.

How to solve this ?

I have two ways for solving error routing on Laravel 8

  1. Change your route with the new laravel documentation
  2. or, Keep your route same as Laravel 7 with some changes

Let’s try with first option for changes the routing file.

Refer from https://laravel.com/docs/8.x/routing, now we need to set full named on routing like this

Before

Route::get('/', 'NewsController@index');

After

Route::get('/', 'App\Http\Controllers\NewsController@index');

or if we wanna simplify the code, we can use array method like this

use App\Http\Controllers\NewsController;
...

Route::get('/', [NewsController::class, 'index']);

If you thing it too many and painfull for changing the route, we can choose option two which is keep routing same as Laravel 7. What we need to do is adding again namespace to RouteServiceProvider.

open app\Providers\RouteServiceProvider.php and change null value on namespace var to controller like this

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

and update boot function like this

Before

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

    Route::prefix('api')
        ->middleware('api')
        ->group(base_path('routes/api.php'));
});

After

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

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

Save it. and try again. Now your routing are working again.

That’s how to solve error routing after upgrade Laravel 8. Hope it can help. Enjoy.

Leave a Comment

Your email address will not be published. Required fields are marked *