If you have been working in Laravel 5, you may know all your Controller classes are in app/Http/Controllers folder. And if you have newely started working or upgrading on Laravel 8 latest version, you might get error "Target class controller does not exist"
This is becuase in Laravel 8, the default folder for Controllers class is changed to app folder. To see default paths for Laravel controllers and routes, open
app/Providers/RouteServiceProvider.php file. In the
mapWebRoutes() function you can see:
Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php'));
You can see namespace variable is commented in the Laravel 8 application. This means all your Controllers class base path counted in app folders.
/** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ // protected $namespace = 'App\Http\Controllers';
In Laravel 8, developThere are few solutions of this.
1. This is the simple way to solve the issue if you are upgrading project. Simply remove the comment of namespace variable from app/Providers/RouteServiceProvider.php file. This will make your Controllers class default folder to app/Http/Controllers
/** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\Http\Controllers';
2. Provide full path in routes/web.php
<?php Route::get('welcome', 'App\Http\Controllers\[email protected]');
3. Using class name in routes/web.php
<?php use App\Http\Controllers\HomeController; Route::get('welcome', [HomeController::class, 'home']);
I hope this will help you on your initial Laravel 8 setups.
Copyright 2022 HackTheStuff