Laravel 5 : on success Validation Request function

2.2k Views Asked by At

In laravel 5, we can now use the Request classes for input validation like so :

    public function store(StoreItemRequest $request)
    {
        $item = Item::create($request->all());
        return 'success';
    }

When the validation fails, I can get the errors thanks to the response function in the Request class :

    public function response(array $errors) {
       return response()->json(['errors' => $errors]);
    }

But what if the validation succeeds? Is there a function that would get automatically triggered like so :

    public function ????(){
         if($request->ajax())
           return response()->json(['success' => true]);
    }

Note: it is required that the content of the function store does NOT get executed if the request is ajax (just as it would not get executed if the validation fails).

2

There are 2 best solutions below

6
On BEST ANSWER

Yeah, I found validate method in ValidateWhenResolvedTrait which you could override in your form request class;

public function validate(){

     $instance = $this->getValidatorInstance();

      if($this->passesAuthorization()){
             $this->failedAuthorization();
       }elseif(!$instance->passes()){
              $this->failedValidation($instance);
      }elseif( $instance->passes()){

         if($this->ajax())
            throw new HttpResponseException(response()->json(['success' => true]));

      }

}
4
On

Currently there is no such method. You can do this in your request with some "hacks" (like override validate method) but I do not recommend it.

Idea of Request was to move validation/authorization out of controller. If you move successful response to Request than we have the same situation as before (well, name changed).

I would suggest to let controller handle ajax too:

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->all());
    if($request->ajax())
       return response()->json(['success' => true]);
    return 'success';
}

Is there a reason why you are trying to achieve this in a request?