Reputation: 43
I try to put a validation in a single-action controller and test the API in postman, but it doesn't show anything.
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class BookableAvailabilityController extends Controller
{
public function __invoke(Request $request)
{
$data = $request->validate([
'from' => 'required|date_format:Y-m-d|after_or_equal:now',
'to' => 'required|date_format:Y-m-d|after_or_equal:from',
]);
}
}
and I defined the route in API file:
Route::get('bookables/{bookable}/availability', 'Api\BookableAvailabilityController')
The route is right as it is shown in the route:list
But the postman show the code 200 says everything is OK
Upvotes: 4
Views: 2546
Reputation: 35
Add these lines after the validator. Errors will be listed out in postman.
if ($validator->fails()) { $message = $validator->errors(); return response()->json(['success' => false, 'message' => 'The given data was invalid.', 'errors' => $validator->errors()], 200); }
Upvotes: 0
Reputation: 8078
$request->validate
method, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.
You can use Validator function .so that you can pass custom response
$validator = Validator::make($request->all(), [
'from' => 'required|date_format:Y-m-d|after_or_equal:now',
'to' => 'required|date_format:Y-m-d|after_or_equal:from',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
Upvotes: 1