I have the User
and Post
models in the project. I want to make the slug
column from Post
unique but not when updating the post
. I found this URL https://laravel.com/docs/5.2/validation#rule-unique
from one of the answers.
I found a solution from the above URL 'slug' => 'unique:posts,slug,'.auth()->id().',user_id'
but this is not exactly what I want. That makes the column not unique only for one user with provided id.
In my case, I want all the admin users to be able to edit editors' or authors' posts without changing the slugs whenever they do.
Validation codes inside update method.
$request->validate([
'title' => 'required|string|max:255',
'slug' => 'required|string|max:255|unique:posts,slug,'.auth()->id().',user_id',
'featured_img' => 'nullable|max:1024|mimes:png,jpg,jpeg',
'excerpt' => 'nullable|string|max:225',
'body' => 'nullable',
]);
CodePudding user response:
Use the Post
rather than a User
when specifying the criteria for unique
.
// include a use statement for Rule
use Illuminate\Validation\Rule;
'slug' => [
'required',
'string',
'max:255',
Rule::unique('posts')->ignore($post->id)
]
Where $post
in the above is the $post
object you're working with in the update
function.
The above obviously doesn't scope the rule to just admins
, but you generally have separate routes/controllers for admin
related functionality. Alternatively, you can conditionally include the rule.