My rule is like below. Please check the composite_unique in the below code
public function rules()
{
return [
'SubCategory' => 'required|max:25|min:5|composite_unique:tblsubcategory,CategoryID',
'CategoryID' => 'required|min:1'
];
}
My update method is like below...
public function update(SubCategoryRequest $request)
{
$SubCat = $this->CacheCollection->getAllSubCategories($request->input('CategoryID'));
$SubCategory = $SubCat->SubCategories->where('SubCategoryID', 1)->first();
$SubCategory->SubCategory = $request->input('SubCategory');
$SubCategory->CategoryID = $request->input('CategoryID');
$SubCategory->save();
}
My Validator class is like below. Please check the composite_unique rule in below code.
class ValidationServiceProvider extends ServiceProvider
{
public function boot() {
$this->app['validator']->extend('composite_unique',
function ($attribute, $value, $parameters, $validator) {
// remove first parameter and assume it is the table name
$table = array_shift( $parameters );
// start building the conditions
$fields = [ $attribute => $value ];
while ( $field = array_shift( $parameters ) ) {
$fields[ $field ] = \Request::get( $field );
}
// query the table with all the conditions
$result = \DB::table( $table )
->select( \DB::raw( 1 ) )
->where( $fields )->first();
return empty( $result ); // edited here
});
}
}
What's the problem
When i try to update the record and don't edit anything and click on update button... I am getting the error that duplicate combination of SubCategory and CategoryID. I think validation code is done just for check before Inserting the new record. For update it is not working.
Below is the Schema of SubCategory Table
CREATE TABLE `tblsubcategory` (
`SubCategoryID` int(11) NOT NULL,
`SubCategory` varchar(25) NOT NULL,
`CategoryID` int(11) NOT NULL,
`IsActive` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblsubcategory`
MODIFY `SubCategoryID` int(11) NOT NULL AUTO_INCREMENT;
Below is Unique Key Constraint
ALTER TABLE `tblsubcategory`
ADD PRIMARY KEY (`SubCategoryID`),
ADD UNIQUE KEY `UK_tblSubCategory_SubCategory_CategoryID` (`CategoryID`,`SubCategory`);
via Chebli Mohamed
1 commentaire:
If you haven't solved yet... here it is:
https://laracasts.com/discuss/channels/requests/laravel-5-validation-request-how-to-handle-validation-on-update
Enregistrer un commentaire