Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

__gregory's avatar

Route model binding with a route prefix

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.

0 likes
5 replies
Nakov's avatar

What if you make it optional? And then throw an exception if it is missing from the methods you need it for, but it will not complain for most of the routes which don't require that parameter but it can still exists there?

Route::prefix('{country?}')
__gregory's avatar

Thanks for your suggestion! I've already tried this, I still get the same error: "App\Http\Controllers\CompanyController::show(): Argument #1 ($company) must be of type App\Models\Company, string given"

__gregory's avatar

Haha I'm actually using this package in my project. However, I first tried to setup a clean Laravel installation and try from there.

Going to take a deep dive in the source code then...

Please or to participate in this conversation.