2

I've tried following this question, which seems like what I want, but have had no luck.

I have a Page model which has an incrementing id, a title, a slug (unique), and an html column. I want to be able to change the title, slug, and html fields. I've tried adding the rule:

'slug' => 'required|unique:pages,slug,{$this->slug}',

for my PATCH request, but when I submit my form (with the same slug), I get an error that it's already taken. If I change the slug, the title and html changes, but the slug does not.

Ideally I'd rather have the slug be generated automatically and update in the background, but I've not been able to get that to work out either.

How can I allow for a changing unique field when updating a model, or generate it automatically?

Community
  • 1
  • 1
sharf
  • 2,123
  • 4
  • 24
  • 47

1 Answers1

3

You need to provide the unique rule with three arguments to add an exception.

  1. The Name of the Table that contains the exception (pages)
  2. The Column Name of the exception (slug)
  3. Primary Key of the row that contains the exception. (id)

In your case the primary key is the id field not the slug field.

'slug' => 'required|unique:pages,slug,' . $this->id
Jeemusu
  • 10,415
  • 3
  • 42
  • 64
  • `$this->id` is null. How do I get the id? – sharf Sep 14 '15 at 13:34
  • That would depend on how you are doing the validation. Are you using a validator class? Handling it in your controller? – Jeemusu Sep 15 '15 at 01:07
  • Is the ID in the URI? `$this->route('id');` If the slug is in the URI, you could retrieve the row using the slug (i assume it's unique), and then return the id from the eloquent object. – Jeemusu Sep 15 '15 at 02:40
  • With something like `Page::where('slug', $this->route('slug'))->first()->id`? – sharf Sep 15 '15 at 04:29
  • 1
    I ended up going with `$this->route('page')->id`. I'm using model binding in my routes.php file so I just needed to grab it and it was my ready made `Page` model. – sharf Sep 15 '15 at 04:43