0

this is PostsRequest.php in http/request:

<?php

    namespace App\Http\Requests;
    
    use App\Post;
    use Illuminate\Foundation\Http\FormRequest;
    use Illuminate\Validation\Rule;
    
    class PostsRequest extends FormRequest
    {
        /**
         * Determine if the user is authorized to make this request.
         *
         * @return bool
         */
        public function authorize()
        {
            return true;
        }
    
        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {
            return [
                'title' => ['required','max:255', Rule::unique('posts')->ignore($this->id)],
                'slug' => ['required', Rule::unique('posts')->ignore($this->id),],
                'content' => 'required',
                'type' => 'required|in:blog,download,page',
                'status' => 'required',
            ];
        }
    }

and this is edit() method in PostController.php

   public function update(PostsRequest $request, $id)
    {

        $validated = $request->validated();
        $validated['user_id'] = auth()->user()->id;
        $post = Post::find($id)->fill($validated);
        $post->save();

        return redirect()->action('PostController@index');
    }

Problem: show error in update page that this value is already exists.
who to resolve problem unique fields in edit form?

Mehdi Jalali
  • 183
  • 1
  • 2
  • 9
  • I'm sorry, but It's very difficult to understand what you're wrote! Please, rewrite all trying to be more clear about what you're trying to do and what problems you have, providing the error messages and off course all code that involves the problem! Thanks! – Andre Carneiro Aug 08 '20 at 13:45

2 Answers2

2

Problem Solved

change:

Rule::unique('posts')->ignore($this->route('id'))

with:

Rule::unique('posts')->ignore($this->route('post'))
Mehdi Jalali
  • 183
  • 1
  • 2
  • 9
  • I had problem in Laravel 8 how to define this option when I'm using update via API and fields are not same, and also not using ID as determined parameter for user. If you are using slug, and URL parameter is not ID, maybe user/{slug} you can set up in Request file rule like this: `Rule::unique('users', 'email')->ignore($this->route('manage_user'), 'slug')` `Users` is table, `email` is column, `manage_user` is route parameter and `slug` is column that Rule will check. – kkatusic Dec 10 '21 at 10:33
1

If you're wanting to resolve the $id from the route then you can use the route() method in your request class e.g.

Rule::unique('posts')->ignore($this->route('id'))
Rwd
  • 34,180
  • 6
  • 64
  • 78
  • @MehdiJalali It's included in my answer: `$this->route('id')`. Replacing the `unique` rule you have with the one in my answer should solve your issue. – Rwd Aug 08 '20 at 09:41