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>
To exclude the current model from the check, pass the id as the 3rd
column.
'name' => 'required|unique:categories,name,'. $this->id
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With