M
M
Maxim2020-05-28 12:30:33
Laravel
Maxim, 2020-05-28 12:30:33

How to return Request validator response in Laravel in json?

there is LocalizationRequest

public function rules()
    {

        return [
            'name' => ['required', 'string', 'max:255'],
            'code' => ['required', 'string', 'max:255'],
            'locale' => ['required', 'string', 'max:255'],
            'image' => ['required', 'string', 'max:255'],
        ];
    }


tell me how to return the result to me in this form

return response()->json([
'error' => 0,
'message' => validation result
])

tried something like this, but it doesn't work

public function store(LocalizationRequest $request)
    {
                $v = $request->validated();
                $errors_m = '';
                if ($v->fails())
                {
                    $errors = $v->errors();
                    foreach ($errors->all() as $error){
                        $errors_m.= $error;
                    }
                    return response()
                        ->json([
                            'message' => $errors_m,
                            'error' => 1,
                        ], 200);
                }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-05-28
@Aslero

LaravelRequest will automatically return errors and a code in the response. Those. you can not write bicycles.
Get errors in js script (VUE framework)

// аякс запрос
.catch((error)=> {
  this.errors = error.response.data.errors;
});

count errors in computed
errors_count: function () {
   return Object.keys(this.errors).length;
},

errors_count will be available

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question