Implicit Route Model Binding
Laravel's implicit route model binding isn't working. It is not looking up the record indicated by the identifier. I'm getting a brand new model object.
Given this code:
Route::get('users/{user}', function (App\User $user, $id) {
$user2 = $user->find($id);
return [
[get_class($user), $user->exists, $user],
[get_class($user2), $user2->exists],
];
});
And this URL: /users/1
I get this output:
[["App\\User",false,[]],["App\\User",true]]
I'm on PHP 7.2 and Laravel 5.6.
Additional Information
I've successfully accomplished implicit route model binding in other Laravel projects. I'm working on an existing codebase. As far as I can tell, the feature hasn't been used previously.
The user record exists. It has not been soft deleted. The model does not use the SoftDeletes
trait.
I've tried this using various unique route names and other models.
I've checked the App\Http\Kernel
class for the usual culprits. $middlewareGroups
has \Illuminate\Routing\Middleware\SubstituteBindings::class,
in the web
section and $routeMiddleware
contains 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
.
Answer
I finally resolved this issue. The routes in routes/web.php
did not have the web
middleware. This is normally done in app/Providers/RouteServiceProvider.php
in the mapWebRoutes()
function. At some point, during a Laravel upgrade, the route definition got mangled. It looked like this:
Route::group([
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
It could have been updated, using that older definition style, to look like this:
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
], function ($router) {
require base_path('routes/web.php');
});
Instead, I just copied the latest method chaining style from the laravel/laravel
project, so it now looks like this:
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?