Register Auth Routes in Laravel when using ::class for Controllers

Since Freek Van der Herten tweet about the way to register Controllers in Laravel with the ::class (Introduced in PHP 5.5) a while ago I always did it this way. (TL;DR: Go to Solution)

As we mostly create APIs I used this when register Routes in `routes/api.php` only. Till Today…

When I wanted to set this up, I’d remove the namespace prefix from RouteServiceProvider.php and register all Route’s Controller references via ::class notation.

This was my web.php at this point:

use App\Http\Controllers\HomeController;

Auth::routes();
Route::get('/home', HomeController::class)->name('home');

But the login (and all other Routes, registered in Auth::routes() didn’t work anymore:

Target class [Auth\LoginController] does not exist.

Solution

 

Auth::routes() uses the string notation internally and does expect the default namespace to be set: https://github.com/laravel/framework/blob/6.x/src/Illuminate/Routing/Router.php#L1149

Because of that, you only need to wrap the call into a Route Group having the namespace set correctly:

use App\Http\Controllers\HomeController;

Route::group(['namespace' => 'App\Http\Controllers'], function() {
    Auth::routes();
});
Route::get('/home', HomeController::class)->name('home');

Leave a Comment

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

Scroll to Top