I am currently doing a small project to learn some laravel validation and ran into a problem.
The API endpoint is api/test/schoolbook?start= and my validation is
'start' => ['date_format:Y-m-d H:i:s']
While this works like a charm and sorts the schoolbooks by a start year, i think my validation has some error. It validates if start is equal to the defined date format, all good. but if i now parse just ?start=without any thing, it still goes through, but doesn't throw an error message (it just returns everything without sorting)
Is there a way i can validate this better and prevent the query string parameter to be empty?
If start is not passed, it should return all the records, so i cant make it required really.
So the scenarios are:
?start=date is passed in the right format and returns all the schoolbooks by the passed date,
?start=date is not passed and returns all the records in the database
?start= should also return 'has to be in date format validation'
Thank you!
The Controller:
public function findSchoolbook(
SchoolBookRequest $request,
) : JsonResponse {
$schoolbook = $this->schoolkbool->sort($paramBag);
$response = $this->transformer()->paginator($schoolbook);
return $this->response($response);
}
The ParamBg method i use
private function getParamBag(SchoolBookRequest $request) : ParamBag
{
return ParamBag::create()
->setPage($request->get('page'))
->setPerPage($request->get('per_page'))
->setStartDate($request->get('start_at'))
}
The Request
class SchoolBookRequest extends Request
{
public function rules() : array
{
return [
'start_at' => ['date_format:Y-m-d H:i:s']
];
}
}
'start' => ['required', 'date_format:Y-m-d H:i:s']or use the current date if no date is passed?