Reputation: 750
I need an output from laravel request validation error message as a json,
{
message:[{field1 : error message},{..},....{field n : error message}]
}
Upvotes: 0
Views: 123
Reputation: 4137
If you're using Laravel's default app boilerplate, you're all set: Laravel already decides which response type to give when validating request input. If you're using AJAX, it will respond with JSON in a format very similar to what you need; if you're using normal requests, it will redirect to a URL of your choice (or back, by default), flashing errors and input.
All you have to do is make sure your controller extends the default App\Http\Controller.php
and on your validating method do something like this:
public function processMyForm()
{
$rules = [
'email' => 'required|email',
// ...
];
$this->validate(request(), $rules);
// Request is valid, proceed
}
If the request is not valid, the controller will throw an exception, so the code below it will never execute.
If you're not extending the default controller, make sure your custom controller uses the Illuminate\Foundation\Validation\ValidatesRequests
controller trait
.
Upvotes: 1