Home > Enterprise >  Why isn't this unique Laravel validation working?
Why isn't this unique Laravel validation working?

Time:10-14

I've been scouring the internet and laravel docs trying to get this working.

Ideally, I can just use the $request->validate() method. But I've also tried manually making and reporting the errors too (which got me a little closer, but still didn't work everywhere I needed it to).

Here's my situation.

Somebody creates a post. They create a title, and I generate a slug based on that title.

The titles have to be unique. This is working as expected. I always get sent back with a nice error message that the title must be unique.

The slug must be unique too. This could be a problem if someone named a post hello, and then named another post hello!

<form ...>
  <input type="text" name="title" id="title">
</form>

So they submit, and in my controller method, before I do any validation, I add the slug to the request.

$request->slug = Str::slug($request->title);

Then I try the validation

$request->validate([
  'title' => 'required|unique:posts',
  'slug' => 'unique:posts,slug'
]);

In situations like Post-1 and Post 1 or hello and hello! I expect the validation to fail for the slug the same way it has for the title.

But instead, it doesn't, and then I get an SQL error

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'post-1' for key 'posts.posts_slug_unique'

I got it working with Validator::make... But only for the store method. It still didn't work on updates. Also, it wasn't nearly as clean.

Does anybody see what I'm doing wrong?

CodePudding user response:

@uz4ir had the fix for me.

It may not be the best-practice solution, but there are plans for adding custom slug inputs to the form in the future. So this code will be removed in the future.

Other solutions I looked at seemed to be a lot more effort, and I couldn't see any harm in adding the slug to the request at this point.

Changing

$request->slug = Str::slug($request->title);

to

$request->request->add(['slug' => Str::slug($request->title)]);

works great.

  • Related