jeudi 22 février 2018

Unique record but only for a given parent in Laravel 5.5

I have 2 database models, both with a field for URL so you can access them. In the frontend I'd do something like this to access it:

//

Validating that the parent URL is easy, I just ensure it's required and unique for that table. But the child one is a bit tricker. I need the URL to be unique but only if the records share the same parent. Currently my validation rule for creating a new record is:

'url' => 'required|alpha_dash|unique:child_table,url',

and updated with:

'url' => 'required|alpha_dash|unique:child_table,url,' . $id,

But that means EVERY URL must be unique and I'd rather not enforce that rule. I know the parent record ID so is there a way to say URL must be unique but only for records with this parent ID?

To be absolutely clear, this isn't allowed:

/parent1/child1
/parent1/child1

But this is:

/parent1/child1
/parent2/child1



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire