skip to Main Content

Consider the following example:

Route::get('/users/profile/{id?}', [UserController::class, 'getSoleUserProfile']);


class UserController extends Controller
{

    public function getSoleUserProfile(
        ?int $id = null,
        UserInterface $users,
    ) {
        ...
    }
}

So the $id is an optional parameter, but it gives me the following error:

App\Http\Controllers\UserController::getSoleUserProfile(): Argument #1 ($id) must be of type ?int, App\Domain\User\UserService given

If I make it required it works good, am I doing something wrong?

P.S. UserService is an implementation of UserInterface

2

Answers


  1. when you want to pass an optional variable, you need to have the optional variable in the last parameter of the controller method you want to call.

    since you will probably want to pass the request to the controller as well, the following code could help you to get what you want to achieve.

    public function getSoleUserProfile(
         Request $request,
         UserService $users,
         ?int $id = null
     ) {
            ...
       }
    
    Login or Signup to reply.
  2. The error message you received indicates that the second parameter you passed to the getSoleUserProfile() method, UserInterface $users, is being interpreted as the first argument instead of the optional $id parameter. This suggests that the $id parameter may not be receiving the expected value or type.

    To resolve this issue, you could try adjusting the order of the parameters in the getSoleUserProfile() method so that $id is the first parameter, followed by $users:

    public function getSoleUserProfile(
        int|null $id = null,
        UserInterface $users
    ) {
        // ...
    }
    

    Note that I’ve also changed the type declaration for $id to use the int|null type instead of ?int. Both are equivalent, but the former is the more commonly used syntax.

    By making this change, you should be able to call the method with either an $id value or a null value, and the $users parameter should be correctly interpreted as the second parameter.

    If you still encounter issues, you may want to check the implementation of the UserInterface class to ensure that it is compatible with the type hint for the $users parameter.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search