lundi 25 septembre 2017

How to add extra data in response if Validation fails in FormRequest Laravel

I need to add custom tag in response if the validation fails in FormRequest.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreMessage 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 [
            'name' => 'required|max:100',
            'email' => 'required|email',
            'message' => 'required|max:1000'
        ];
    }

    public function withValidator(\Illuminate\Validation\Validator $validator)
    {
        $validator->after(function ($validator) {

               if($validator->fails()) {
                   $validator->errors()->add('status', 'error');
               }

        });
    }

}

If my any of the validation fails only then I need to add status = error in json response else I need to add status = success.

Also my response status is nested under errors tag I need it to be at level 0.

{"message":"The given data was invalid.","errors":{"name":["The name may not be greater than 100 characters."],"status":["error"]}}

Purpose of this is I am sending Ajax request to submit a form i need a flag to identify whether error occurred or not. Is there any better way to do this. Pardon me if I am asking silly question. I am newbie to laravel. Any help would be appreciated.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2wPeADW
via IFTTT

Aucun commentaire:

Enregistrer un commentaire