I'm working with Laravel nested resources to serve a many-to-many relationship. I'm working on a Football app and I want to link Competitions with Seasons, e.g. Premier League with 2021/22 season.
What I want to achieve is to have a dedicated route to manage this relationship with Seasons being sub-resources of Competitions.
My entities have an auto-generated integer ID at database level, but I'm using getRouteKeyName() to define the slug as the field to be used by Laravel for implicit model binding.
Now I'm struggling to make the validation work when posting a new Season under a Competition. The request looks like this:
POST /api/competitions/premier-league/seasons/
{
"season": "21-22",
...
}
The value "21-22" is the actual slug for the Season object, but I can't manage to use it for validation in the association table, as foreign keys in it use auto-generated ones rather than the column I use for implicit model-binding.
To clarify, the tables look like this:
seasons competition_editions competitions
id slug id comp season id slug
X 21-22 Z Y X Y premier-league
Is there a way to make the unique rule of FormRequest work with model-binding key so that I don't have to manually convert the slug to the actual id of the resource inside the controller?
Thank you!
seasonsorcompetition_editions? If it's the latter then you can look at unique validation under the part that says Adding Additional Where Clauses