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

cwhite's avatar
Level 19

Override route scoped binding relationship convention

Hello,

I have a parent/child model that doesn't follow the Laravel naming convention (legacy, can't change it). And I'm trying to use the Route::apiResource('stations.logs', ...)->scoped(). However, Laravel is complaining that it can't find the logs relationship on the parent model (because it's named something else).

Is there a way to override the relationship name for scoped routes?

From the docs:

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the Photo model has a relationship named comments (the plural of the route parameter name) which can be used to retrieve the Comment model.

Thanks!

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, you can override the relationship name for scoped routes by defining a resolveChildRouteBinding method on the parent model. This method should return the child model instance based on the given route key name.

Here's an example implementation for the parent model:

class ParentModel extends Model
{
    public function resolveChildRouteBinding($childType, $value, $field)
    {
        if ($childType === 'logs') {
            return $this->logs()->where('id', $value)->firstOrFail();
        }
        
        return parent::resolveChildRouteBinding($childType, $value, $field);
    }
    
    public function logs()
    {
        return $this->hasMany(Log::class);
    }
}

In this example, we're checking if the child type is logs, and if so, we're returning the child model instance based on the id route parameter. If the child type is not logs, we're calling the parent implementation of resolveChildRouteBinding.

Note that we're assuming that the child model has an id primary key. If your child model uses a different primary key, you'll need to adjust the where clause accordingly.

With this implementation, you should be able to use the Route::apiResource('stations.logs', ...)->scoped() method with your custom relationship name.

1 like

Please or to participate in this conversation.