I have a table and columns associated with that table. I can delete columns using this controller method:
public function destroy(Grid $grid, GridCol $gridCol)
{
$this->deleteRowOrCol($grid, $gridCol);
return $gridCol;
}
However, I need to add validation that prevents me from deleting that column if the number of columns = 1 (in other words, if the length of grid->grid_cols === 1.)
Note that $grid is of the following structure (simplified):
$grid = {
"id": 5,
"name": "DSFGEA",
"client_id": 1,
"last_grid_col": {
"id": 41,
"grid_id": 5,
"order": 2,
"header": "ABC",
},
"grid_cols": [
{
"id": 42,
"grid_id": 5,
"order": 1,
"header": "WER",
},
{
"id": 41,
"grid_id": 5,
"order": 2,
"header": "ABC",
}
],
}
And $gridCol is retrieved using:
$grid->gridCols()->where('order', $request->input('order'))->firstOrFail()
I know how to add validation with a minimum number in the array:
public function destroy(Grid $grid, GridCol $gridCol)
{
$validatedValues = $this->validate($grid, [
"grid_cols" => "required|array|min:1",
]);
$this->deleteRowOrCol($validatedValues, $gridCol);
return $gridCol;
}
However, that’s not quite what I aim to do. How would I be able to update or add to the code below to prevent users from deleting a grid column when the number of grid_cols === 1?
CodePudding user response:
public function destroy(Grid $grid, GridCol $gridCol)
{
$validatedValues = $this->validate($grid, [
"grid_cols" => "required|array|integer|gt:1",
]);
$this->deleteRowOrCol($validatedValues, $gridCol);
return $gridCol;
}
CodePudding user response:
I found this solution to be effective since it directly counts how many grid columns are there and throws a 422 if there's 1 item in the gridCols array:
if (count($grid->gridCols) === 1)
abort(422, 'Cannot delete last table column');
else {
$this->deleteRowOrCol($grid, $gridCol);
return $gridCol;
}
CodePudding user response:
No need to use custom validation, by default laravel provided
$validatedData = Validator::make($request->all(),[
'grid_cols' => ['required','array','min:2'],
]);
if($validatedData->fails()) {
return response()->json(['message' => 'No Delete the grid!','errors' => $validatedData->getMessageBag()->toArray()], 400);
}