Updating a Laravel model with a unique field

10,581

Solution 1

Ok, so this worked for me:

In my UpdateCategoryRequest:

public function rules()
    {
        $rules = Category::$rules;
        if ($this->isMethod('patch'))
        {
            $id = $this->categories;
            $rules['name'] = $rules['name'].',name,'.$id;
        }
        return $rules;
    }

Solution 2

To exclude the current model from the check, pass the id as the 3rd column.

'name' => 'required|unique:categories,name,'. $this->id

Solution 3

In your request, just append to the 'name' rule you get from the model.

public function rules()
{
    $rules = Category::$rules;
    $rules['name'] .= ','. $this->route('id');
    return $rules;
}
Share:
10,581
showFocus
Author by

showFocus

Updated on June 08, 2022

Comments

  • showFocus
    showFocus almost 2 years

    I am unable to update a model, if it has a unique field. I get the message "The name has already been taken."

    My controller:

    /**
     * Update the specified Category in storage.
     *
     * @param  int              $id
     * @param UpdateCategoryRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateCategoryRequest $request)
    {
        $category = $this->categoryRepository->findWithoutFail($id);
    
        if (empty($category)) {
            Flash::error('Category not found');
    
            return redirect(route('categories.index'));
        }
    
        $category = $this->categoryRepository->update($request->all(), $id);
    
        Flash::success('Category updated successfully.');
    
        return redirect(route('categories.index'));
    }
    

    UpdateCategoryRequest

     /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return Category::$rules;
    }
    

    Category Model

        /**
     * Validation rules
     *
     * @var array
     */
    public static $rules = [
        'name' => 'required|unique:categories,name'
    ];
    

    I've tried appending to my rules, the following:

    $this->id
    $id
    
    @include('adminlte-templates::common.errors')
           <div class="box box-primary">
               <div class="box-body">
                   <div class="row">
                       {!! Form::model($category, ['route' => ['categories.update', $category->id], 'method' => 'patch']) !!}
    
                            @include('categories.fields')
    
                       {!! Form::close() !!}
                   </div>
               </div>
           </div>