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

eggplantSword's avatar

Call to a member function getBags() on string

I'm using inertia and in the shared data I want to send the errors but as an array in case there are multiple errors to display. The code I have used to work but now in my new project isn't working and I'm not sure why.

This is my code

return array_merge(parent::share($request), [
            'app' => [
                'name' => config('app.name'),
            ],
            'auth' => $auth,
            'flash' => [
                'success' => Session::get('success'),
                'info' => Session::get('info'),
            ],
            'errors' => Session::get('errors') ? Session::get('errors')->getBag('default')->getMessages() : (object)[],
        ]);

This is how I'm trying to return the errors

return back()->with('errors', ['The email or password is incorrect.']);

This gives me the following error

Call to a member function getBag() on array

If I try like this instead

return back()->with('errors', 'The email or password is incorrect.');

I get this error

Call to a member function getBag() on string

How can I get this to work?

0 likes
1 reply
Nakov's avatar

The issue is that this one: Session::get('errors') returns either array or a string from whatever you return as this ->with() puts whatever you ask for in a flash session.

So this:

'errors' => Session::get('errors') ? Session::get('errors')->getBag('default')->getMessages() : (object)[],

should be just this:

'errors' => Session::get('errors') ?? [],

don't call -getBag() on that one. Unless you use it this way: https://laravel.com/docs/8.x/validation#named-error-bags

Note: withErrors and the second parameter is the name of the bag.

Please or to participate in this conversation.