dark_illusion_909099
dark_illusion_909099

Reputation: 1099

Laravel redirect with input and with errors not working

I am having issues with getting the ->withInput() and ->withErrors() to work so that upon a validation failure I can retrieve these in the blade.

This is what I have in the controller:

$rules = array(
   'mobile' => 'required'
);

$validator = Validator::make($request->all(), $rules);

if ($validator->fails()) {
    $fieldsWithErrorMessagesArray = $validator->messages();
    $fieldsWithErrorMessagesArray = $fieldsWithErrorMessagesArray->messages();

    $formattedErrorArray = array();
    foreach ($fieldsWithErrorMessagesArray as $key => $error) {
       $formattedErrorArray[$key] = $error[0];
    }

    return redirect()->back()->withInput()->withErrors($formattedErrorArray);
}

However in the blade when var_dump the $errors, I am getting this:

object(Illuminate\Support\ViewErrorBag)#267 (1) { ["bags":protected]=> array(0) { } }

If I were to dd($fieldsWithErrorMessagesArray), it will give me:

array:7 [▼
  "mobile" => array:1 [▼
       0 => "The mobile field is required."
  ]
]

I also tried this way :

$test = array(
            'mobile' => 'No jobs found. Please try searching with different criteria'
        );

return redirect()->back()->withInput()->withErrors($test);

This worked and I am not sure why the other one doesn't work. With this test array the blade file looks like this :

object(Illuminate\Support\ViewErrorBag)#264 (1) { ["bags":protected]=> array(1) { ["default"]=> object(Illuminate\Support\MessageBag)#265 (2) { ["messages":protected]=> array(2) { ["mobile"]=> array(1) { [0]=> string(59) "No jobs found. Please try searching with different criteria" }} ["format":protected]=> string(8) ":message" } } }

This is how my blade file looks like:

@if ($errors->has('mobile'))
                                        @foreach($errors->get('mobile') as $error)
                                            <span class="validation_error">{{$error}}</span>
                                        @endforeach
                                    @endif
                                    <div class="form-group">
                                        <div class="input-group mb-2">
                                            <div class="input-group-prepend">
                                                <div class="input-group-text"><i
                                                            class="fas fa-mobile-alt text-info"></i>
                                                </div>
                                            </div>
                                            <input type="number" class="form-control" value="{{old('mobile')}}" name="mobile"
                                                   placeholder="Mobile Number">
                                        </div>
                                    </div>

I also have var_dump to see any errors brought back :

<?php
   echo var_dump($errors) . "</br>";
?>

Below I have provided how the Kernel.php file looks:

protected $middleware = [
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];



protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];




protected $middlewarePriority = [
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\Authenticate::class,
    \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    \Illuminate\Auth\Middleware\Authorize::class,
];

Upvotes: 3

Views: 3024

Answers (1)

Hafez Divandari
Hafez Divandari

Reputation: 9029

Why don't you just use "Automatic redirection":

$validator = Validator::make($request->all(), array(
   'mobile' => 'required'
));

$validator->validate(); // automatically redirects if validation fails

You may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected.

Here is the full doc: https://laravel.com/docs/master/validation#automatic-redirection

Note 1: Make sure that Illuminate\View\Middleware\ShareErrorsFromSession middleware is listed on your web middleware group on \app\Http\Kernel.php file (full docs).

Note 2: Laravel will check for errors in the session data, so check session driver on \config\session.php and SESSION_DRIVER property on .env file to be set up. Try different drivers and check if it works.

Upvotes: 2

Related Questions