Odunayo Ogungbure
Posted on September 16, 2020
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.
Posted on September 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 28, 2024