Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a Laravel model with a unique field

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>
like image 840
showFocus Avatar asked Jan 05 '23 18:01

showFocus


2 Answers

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

'name' => 'required|unique:categories,name,'. $this->id
like image 153
Ohgodwhy Avatar answered Jan 19 '23 01:01

Ohgodwhy


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;
}
like image 37
lagbox Avatar answered Jan 19 '23 00:01

lagbox