I am using Laravel request to validate in my controller the requested data
and here is my request file data
I am facing two challanges
- first I am not able to return custom message using static function
- I am not able to send single message as we send in controller validation using errors()->first().
By defalut it is returning like that
but I want like below SS
Is there I can send first message using request ?
CodePudding user response:
If you are using laravel 8 or 9 you can do that using the attribute $stopOnFirstFailure
of your FormRequest Class
class UpdateRequest extends FormRequest
{
/**
* Indicates whether validation should stop after the first rule failure.
*
* @var bool
*/
protected $stopOnFirstFailure = false;
//...
}
as for the response rendering, you need to add a custom render/format in your exception handler (App/Exceptions/Handler.php) to catch the validation exception thrown and return the json format you need.
CodePudding user response:
-For custom message
Laravel Documents customizing-the-error-messages
-For return single error message
//In Request
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'success' => false,
'message' =>$validator->errors()->first(),
'data' => null,
], 422));
}