In Laravel what is correct way to do route parameter validation to ensure the id
(GET) is numeric?
I am currently doing this way:
public function run($id, Request $request)
{
if (!is_numeric($id)) {
return response()->json([
'success' => false,
'message' => 'ID must be numeric'
]);
}
// Do something else
}
Do it in your routes themselves, using a regular expression constraint.
Route::get('user/{id}', function ($id) {
//
})->where('id', '[0-9]+');
The ->where('id', '[0-9]+')
will cause the route to only be valid for numeric values of id
. Accessing user/foo
will result in a 404.