FatSam8
FatSam8

Reputation: 43

The validation in api doesn't work in postman for my laravel project

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

enter image description here

But the postman show the code 200 says everything is OK

enter image description here

Upvotes: 4

Views: 2546

Answers (2)

Nixon Darius
Nixon Darius

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

Vision Coderz
Vision Coderz

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

Related Questions