Consider the following routes and controllers:
Route::get('companies', [CompanyController::class, 'index'])->name('companies.index');
Route::get('companies/{company}', [CompanyController::class, 'show'])->name('companies.show');
use App\Models\Company;
class CompanyController
{
public function index()
{
return Company::all();
}
public function show(Company $company)
{
return $company;
}
}
This is nothing special and works perfectly when accessing mysite.test/companies/1
Now I want to add a country route prefix for each route. So I am wrapping my initial definitions like this:
Route::prefix('{country}')->middleware('country')->group(function () {
Route::get('companies', [CompanyController::class, 'index'])->name('companies.index');
Route::get('companies/{company}', [CompanyController::class, 'show'])->name('companies.show');
});
Now when I access mysite.test/de/companies/1 I obviously get an error:
"App\Http\Controllers\CompanyController::show(): Argument #1 ($company) must be of type App\Models\Company, string given"
This is easlily solved by changing the method signature to:
public function show(string $country, Company $company)
{
return $company;
}
In my current project I have hundreds of controller methods using route model binding and I would only need to access the $country variable in very few of them.
Is there a way to omit the $country parameter or to tell Laravel to resolve it differently?
I've tried a few things in my middleware like URL::defaults(['country' => 'some-value']); but this only seems to help with URL generation.