Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validator throws an exception instead of redirecting back

After I upgraded to Laravel 5.2 I encountered a problem with the laravel validator. When I want to validate data in a controller take for example this code.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class ContactController extends Controller
{
    public function storeContactRequest(Request $request)
    {
        $this->validate($request, [
            '_token' => 'required',
            'firstname' => 'required|string'
            'lastname' => 'required|string'
            'age' => 'required|integer',
            'message' => 'required|string'
        ]);

        // Here to store the message.
    }
}

But somehow when I enter unvalid data it will not redirect me back to the previous page and flash some messages to the session but it will trigger an exception and gives me a 500 error page back.

This is the exception I get. I have read in the documentation that the ValidationException is new instead of the HttpResponseException but I don't know if it has anything to do with this.

[2016-01-05 11:49:49] production.ERROR: exception 'Illuminate\Foundation\Validation\ValidationException' with message 'The given data failed to pass validation.' in /home/vagrant/Code/twentyre-webshop/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php:70

And when I use a seperate request class it will just redirect back with the error messages. It seems to me only the validate method used in a controller is affected by this behaviour.

like image 864
DB93 Avatar asked Jan 05 '16 11:01

DB93


1 Answers

For laravel 5.2 I had to add this line:

    if ($e instanceof ValidationException) 
    {
         return redirect()->back()->withInput();
    }

In App\Exceptions\Handler.php,and the following headers:

    use Illuminate\Session\TokenMismatchException;
    use Illuminate\Database\Eloquent\ModelNotFoundException;
    use Symfony\Component\HttpKernel\Exception\HttpException;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    use Illuminate\Validation\ValidationException;
    use Illuminate\Auth\AuthenticationException;
like image 122
Eduardo Lemus Avatar answered Sep 30 '22 23:09

Eduardo Lemus