Taintedmedialtd
Taintedmedialtd

Reputation: 896

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:

/{{ $parent->url }}/{{ $child->url }}

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

Upvotes: 1

Views: 1482

Answers (2)

Nikola Gavric
Nikola Gavric

Reputation: 3543

Something like this can help you achieve that:

Rule::unique('child_table', 'url')->where(function ($query) use ($parentId) {
    return $query->where('parrent_id', $parentId);
})

Upvotes: 4

Taintedmedialtd
Taintedmedialtd

Reputation: 896

It ended up ever so slightly more complicated if anyone ever needs this:

'url' => ['required', 'alpha_dash', Rule::unique('child_table', 'url')->where(function($query) use ($parentId) {
    return $query->where('parentId', '=', $parentId);
})],

Upvotes: 0

Related Questions