Search code examples
laravelvalidationuniquerules

Unique validation in Laravel depending by User ID


In my books app, I have the following rule on store request:

'title' => 'unique:books,title|required|min:3|max:128,' . $this->user()->id.',user_id',

At this moment, with that validation rule in StoreRequest, I have the error "This title has already been added" (thats correct, but the title was added by a different user, not by the one who's trying to add it).

What I want to achieve is to have a unique rule for title, but only for this user collection. For example: 2 different users can declare the SAME book title, but the same user cannot duplicate it.

What's wrong?


Solution

  • try this:

    'title'      => 'required|string|unique:tblbooks,id,'.$request->input('title'),