logo
podcast Podcast
get help Get Unstuck

Two other ways to fix Postgres route model binding behavior

And why I like them better

Joel Clermont
Joel Clermont
2025-09-17

I shared one reader's solution to the Postgres model route binding issue, but today I want to share two other possible approaches.

The first approach is to override the resolveRouteBinding method on your model:

// app/Models/User.php
public function resolveRouteBinding($value, $field = null)
{
    if ($field === null) {
        $field = 'id';
    }
    
    if ($field === 'id') {
        $value = (int) $value;
    }
    
    return $this->where($field, '=', $value)->firstOrFail();
}

One advantage of this approach is that it's customizing the actual source of the problem, route model binding, and not waiting for an exception to be thrown and then catch it. Now if a non-integer is passed in the URL, it will be cast to an integer, becoming 0 and just failing to match any model at all, resulting in a 404.

That type casting is essentially what MySQL is doing behind the scenes already, so this makes Postgres behave the same way.

The downside is that you have to do it on every model where you want this behavior, and it only works for one field at a time.

Another approach is to filter the route parameter when defining the route:

// routes/web.php
Route::get('/users/{user}', [UserController::class, 'show'])
    ->where('user', '[0-9]+');

This uses Laravel's built-in route parameter constraints to ensure that the user parameter only matches numeric values.

In this case, if someone requests /users/abc, it won't even match our route, and Laravel will return a 404 right away without any database look up at all.

This approach has the advantage of being very explicit and easy to understand. It also avoids any unnecessary database queries for invalid input. The downside is that you have to remember to add the constraint to every route that uses that model binding.

Here to help,

Joel

P.S. Don't leave security as an after-thought in your Laravel application. Download our free ebook: 7 Steps to a Secure Laravel App.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.