With the release of Laravel 8, there has been a change to the routing syntax which might catch you by surprise, at least it did to me. It wasn't under the high or low impact changes so I skipped reading to the end and it came back to haunt me.
In a fresh laravel 8 install, I have this in my web.php
file:
Route::get('/', 'HomeController@index');
and this in the index method of the HomeController.php
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('welcome');
}
This should be very familiar and we'd be expecting a view when we visit the /
route. Rather what we see is an error page
You might start thinking you messed thing up, but no you didn't. Rather, in laravel 8 this syntax doesn't work by default. In the upgrade guide, it was mentioned but the likelihood of impact was optional ๐คจ. Though this was mentioned:
In most cases, this won't impact applications that are being upgraded because your RouteServiceProvider will still contain the $namespace property with its previous value. However, if you upgrade your application by creating a brand new Laravel project, you may encounter this as a breaking change.
The way to define your routes in laravel 8 is either
use App\Http\Controllers\HomeController;
// Using PHP callable syntax...
Route::get('/', [HomeController::class, 'index']);
OR
// Using string syntax...
Route::get('/', 'App\Http\Controllers\HomeController@index');
A resource route becomes
Route::resource('/', HomeController::class);
This means that in laravel 8, there is no automatic controller declaration prefixing by default.
If you want to stick to the old way, then you need to add a namespace property in the RouteServiceProvider.php
(This property was present in previous versions) and activate in the routes method.
/**
* 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';
// Edit boot method
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$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'));
});
To recap, in laravel 8 you can use the new syntax to define your routes or stick to the old way.
Oldest comments (4)
I recently came across this problem. Do you know why they made the change? I can't really find anywhere on the internet that mentions the benefits
I can't really say ๐คท๐พโโ๏ธ
The change was made for the purpose of intellisense.
but of what? It is well intellisensed before in both VSC and PhpStorm world.