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;

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.



Auth::routes() uses the string notation internally and does expect the default namespace to be set:

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() {
Route::get('/home', HomeController::class)->name('home');

Leave a Reply

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

Scroll to Top