Home > Mobile >  Laravel - How to not pass unused parameter in controller
Laravel - How to not pass unused parameter in controller

Time:09-30

I have a route for example -

Route::get('/api/{user}/companies/{company}', [CompanyController::class, 'getCompanies'])

and a function in this controller

public function getCompanies(User $user, Company $company) {
    $companies = $company->all();
    return response()->json(['companies' => $companies]);
}

I am not using the $user instance in the function and I would like to not pass a User $user param in it, but I want that the route has user id as a param for clarity on the frontend. I found a solution of using middleware with the forgetParameter() method but I don't want to add new middleware or declare it only for this route.

I can just leave that unused param in my function and everything will work just fine, but I am curious is there some elegant solution for this case.

CodePudding user response:

I think you can put a _ instead of passing a parameter, but I could be wrong.

CodePudding user response:

public function getCompanies(Company $company, ?User $user = null) 
{
    return response()->json(['companies' => $company->all()]);
}

Pass $user to the last position and give it a default value

  • Related