Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing errors in a controller from a redirect Laravel

As you may expect, when validation fails, I created a redirect.

return Redirect::to('search')->withErrors($v->messages())

I can access it in the view with out a problem, but I would like to do something different. I have an ErrorPartial.blade.php, which I would like to be passed to my search view.

return View::make('search.searchForm')
        ->with('title', 'Search Page')
        ->with('components', Subject::select('Component')->distinct()->get())
        ->with('measurementRow',$measurementRow)
        ->with('races', Race::parseRaceTable())
        ->with('errorPartial', View::make('errorPartial')
                ->with('errors',$v->messages())
                ->render())
        ;

The Problem is I don't have access to $v in this controller function. Can I access the errors that are going to be passed to the view some how? I've tried this:

return Redirect::to('search')->withErrors($v->messages())
            ->with('v', $v);

But I get this error.

Serialization of 'Closure' is not allowed

I could just create the Partial view in my search view but I was wondering if their was a way to do it this way. If anyone knows which would be more efficient or GPP then I wouldn't mind knowing that as well.

Thanks

like image 692
rich green Avatar asked Apr 17 '14 15:04

rich green


2 Answers

Laravel stores the errors in the Session.

And all the functions available in blade are coming from ViewErrorBag class.

use Illuminate\Support\ViewErrorBag;
...
$errors = session()->get('errors', app(ViewErrorBag::class));

This approach is preferred because it returns empty error bag if there is no errors in the session. It means that you can call $errors->any() on this object without expecting to have an error saying

Call to a member function any() on null

You can always find an implementation in source code following this advice

The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.

Documentation

like image 53
Yevgeniy Afanasyev Avatar answered Nov 10 '22 07:11

Yevgeniy Afanasyev


Answering the question to close it as an open question.

Laravel stores the errors in the Session, which can be access like so:

$errors = Session::get('errors');
like image 27
rich green Avatar answered Nov 10 '22 07:11

rich green