laravelvalidationerror-handlinglaravel-5.6laravel-5.7

laravel api not showing message from request validation


im having problems with error handler in my backend laravel api, don't show error message from validation.

routes/api

<?php
Route::group([

    'middleware' => 'api',

], function ($router) {
    Route::post('access/sign-up', 'AuthenticationController@signUp');
});

AuthenticationController

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\SignUpRequest;
use Illuminate\Http\Request;
use App\User;


    class AuthenticationController extends Controller
    {
        /**
         * Create a new AuthenticationController instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth:api', ['except' => ['signUp']]);
        }


        /**
         * 
         *
         * @return \Illuminate\Http\JsonResponse
         */
        public function signUp(SignUpRequest $request)
        {
            //User::create($request->all());
            return response()->json([
                'data' => 'Usuario creado correctamente.'
            ]);
        }
    }

SignUpRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SignUpRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'firstName' => 'required',
            'password' => 'required',
        ];
    }


}

The thing is that when by postman i send password in blank or not send mail for example it send me to main page insted of sending me a json with all the errors like before. I don't know what to do. I tryed with custom message in SignUpRequest, but that's not the problem, think some kind of redirect in error handler.


Solution

  • Just add that code to SignUpRequest

     use Illuminate\Contracts\Validation\Validator;
     use Illuminate\Http\Exceptions\HttpResponseException;
    
    
    
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json($validator->errors(), 422));
    }