HOW TO RETURN JSON FROM LARAVEL FORM REQUEST VALIDATION ERRORS

OMIDIORA EMMANUEL
1 min readFeb 21, 2021

--

php artisan make:request RequestUserRequest

<?phpnamespace App\Http\Requests;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\Rule;use Illuminate\Contracts\Validation\Validator;use Illuminate\Http\Exceptions\HttpResponseException;class RequestUserRequest extends FormRequest{/*** Determine if the user is authorized to make this request.** @return bool*/public function authorize(){return true;}public function rules() {return ['name'=>'required|min:4|max:100','email'=>'required|unique:users, email','password'=>'required|confirmed',];}/*** Get the error messages for the defined validation rules.** @return array*/protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json(['errors' => $validator->errors(),'status' => true], 422));}}

php artisan make:controller AuthController

in your AuthController:

<?phpnamespace App\Http\Controllers;use App\Http\Requests\RequestUserRequest;// use Illuminate\Http\Request;class AuthController extends Controller
{
//
public function register(RequestUserRequest $request)
{//$user=User::create(['name'=>$request->name,'email'=>$request->email,'password'=>bcypt($request->password)]);return $user;}}

Then you define your route in your api.php

Route::post('register' ,[AuthController::class , 'register']);

--

--

OMIDIORA EMMANUEL
OMIDIORA EMMANUEL

Responses (1)