Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phpMick's avatar

Adding errors to the session array.

Hi,

I am trying to add errors to the session:

}catch (\Exception $
        $arrErrors[0] = $e->getMessage();
        $request->session()->put('errors', $arrErrors);
    }

Then I try and use them in blade:

@if($errors->any())

But I get the error:

Fatal error: Call to a member function any() on string

Any ideas?

0 likes
6 replies
d3xt3r's avatar

dd($errors) in template. Is it an object, does it have any() method ?

How are you passing it to the view ?

phpMick's avatar

It appears to be just a string, that is why it fails.

But in the controller, it is an array:

$request->session()->get('errors')

array ( 0 => 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select * from things' at line 1 (SQL: select * from migrations; select * from things)', )

ps I'm throwing this error on purpose

d3xt3r's avatar

@phpMick You are trying to mix-in how laravel handle errors/session/flash and your custom implementation.

If you wan't to add more errors to session and make it available to your templates, preferred way is to do it how laravel does it

$this->session->flash(
            'errors', $this->session->get('errors', new ViewErrorBag)->put($key, $value)
        );

or you can put in session your custom error key, make it available to views by way of middleware and use it.

phpMick's avatar

So, which is the best way to do it?

I'm tempted to just pass an array of errors to my view.... but it would be great to have a solution I use in lots of places.

Should I be putting my own errors in flash, or just putting my own array in the session?

"or you can put in session your custom error key, make it available to views by way of middleware and use it."

Not sure how I make it available to me views, can you point me to the docs somewhere please?

Mick

phpMick's avatar

How about a redirect with errors? Just got this working and it is looking good.

d3xt3r's avatar
d3xt3r
Best Answer
Level 29

That's the easiest and most preferred way to go about it :) Just that it will work with all sort of redirect-response only. (ignore the last part, if that doesn't concern you)

Please or to participate in this conversation.