Cristian
Cristian

Reputation: 382

How to update on laravel request a unique field on validation

I'm trying to edit a form where I have a post with a title, body and slug, the slug is unique, so if I edit and don't update it, it says It alredy have been taken

I'm trying this on my PostRequest validation:

public function rules()
    {
       return [
            'title' => 'required',
            'body' => 'required',
            'metaTitle' => 'required',
            'metaDescription' => 'required',
            'slug' => ['required', Rule::unique('posts')->ignore($this->post)],
        ];
    }

the function on Post controller is:

public function store(PostStoreRequest $request)
    {
        $validated = $request->validated();
        auth()->user()->posts()->create($validated);
        return redirect()->route('articulos.index');
    }

also on my blade update form I have @method('PUT')

Upvotes: 0

Views: 8318

Answers (4)

Milena Grygier
Milena Grygier

Reputation: 396

you should try this:


public function rules()
 {     
       $slug = $this->request->get("slug");

       return [
            'title' => 'required',
            'body' => 'required',
            'metaTitle' => 'required',
            'metaDescription' => 'required',
            'slug' => ['required', Rule::unique('posts')->ignore($slug,'slug')],
        ];
  }

Upvotes: 3

Gurinder singh
Gurinder singh

Reputation: 21

Please try this for both the Store And Update Method:

'slug' => [ 
    'required', 
    'slug', 
    'unique:posts,slug' . (isset($this->post)  ? ',' . $this->post : ' ') 
],

Upvotes: 0

Cristian
Cristian

Reputation: 382

This is the only solution I have found, using my own validator PostRequest doesn't work so for update I validate inside the update function:

public function update(Request $request, $id) {
        $request->validate([
            'slug' => 'required|unique:posts,slug,' . $id,
            'title' => 'required',
        ]);

         $post = Post::find($id);
         $post->fill($request->all());
         $post->save();
        return redirect()->route('articulos.index');
    }

Would be cool to know why this happens and how to solve it, but this is working for now

Upvotes: 0

Bhavesh Tailor
Bhavesh Tailor

Reputation: 243

Try this hope it will work

public function rules(Request $request)
    {
        return [
            'title' => 'required',
            'body' => 'required',
            'metaTitle' => 'required',
            'metaDescription' => 'required',
            'slug' => 'required|slug|unique:posts,slug,' . $this->post,
        ];
    }

Upvotes: 0

Related Questions