phplaravellaravel-5.7

How to pass extra data after validation?


After validation I want to pass some extra data to view. However, I can't send it.

My controller is like,

public function test()
{
    $validator = Validator::make(
        request()->all(), 
        [ 'ziptest' => 'regex:/^([0-9]{3}-[0-9]{4})$/']
    );

    $errors = $validator->errors();

    if($errors->any()) {
        return back()
            ->withErrors($errors)
            ->withTitle('Data From Controller')
            ->withInput();
    }

    return 'success';
}

In my blade I want to check if the title is passed or not. So in my blade view I have

@if($errors->any())
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
@endif

@if(isset($title))
    <p>{{ $title }}</p>
@endif

However, the error portion is displaying properly. But not the title. Why is it not working?

I also tried sending the title in this way.

return back()->withErrors($errors)
    ->with('title','Data From Controller')
    ->withInput();

It is also not working.

I searched in the SO and found several similar questions regarding passing data from controller to view. However, my situation is a bit different.


Solution

  • In your example, you are redirecting back to the previous location. When you use with* for a redirect the information is flashed to the session, rather than made directly available to the view like it would be if you were returning a view instead.

    For it to work with your example, you would have to check session('title') to get the flashed title from the redirect.