framework icon indicating copy to clipboard operation
framework copied to clipboard

[12.x] fix method dependencies order

Open Seb33300 opened this issue 6 months ago • 0 comments

Hello,

Fixes https://github.com/laravel/framework/issues/56047

In the documentation, we can read:

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

What I understand: As long as our controller action param names matches with the routes names, the order of parameters should not matter.

Unfortunately, this is not how it currently works, if our controller actions does not declare param in the same order as the route, this simple example will fail:

class UsersController extends Controller
{
    /**
     * Note: $company is nullable, so we can use the same action with multiple routes
     */
    public function show(User $user, ?Company $company = null)
    {
        var_dump($user);
        var_dump($company);
    }
}

With the following routes :

// That route works as expected
Route::get('users/{user}/details', 'UsersController@show');
// That route trigger an Exception
// Note that the company param is placed first in the URL, while it's in second in the controller action
Route::get('companies/{company}/users/{user}/details', 'UsersController@show');

UsersController::show(): Argument #1 ($user) must be of type User, Company given, called in ...

The exception shows that the params are not passed in the correct order, even if I am using the same param names.

With my PR, that issue is fixed by trying to resolve dependencies by param name first.

Seb33300 avatar Jun 17 '25 03:06 Seb33300