Loading an error message to the next view

63 views Asked by At

I have a controller that is accessing an external API to load data, when a certain page is loaded. Now I wanted to have an error message being displayed when the page is loaded but the external API was not accessible.

To load an error message to the session I am using the response from Pavel Lint to this question to create the following function:

/**
* Add an error array to the MessageBag in the 
* ViewErrorBag of the session
* 
* @param array|null $errors
*/
private static function addErrorsToSession($errors) {
        
   if (!is_null($errors)) {
        $sessionErrors = Session::get('errors', new ViewErrorBag);

        if (! $sessionErrors instanceof ViewErrorBag) {
            $sessionErrors = new ViewErrorBag;
        }

        $bag = $sessionErrors->getBags()['default'] ?? new MessageBag;
        foreach ($errors as $key => $value) {
            $bag->add($key, $value);
        }

        Session::flash(
            'errors', $sessionErrors->put('default', $bag)
        );
    }
}

Then in the controller function to load the view is

/**
* Show the create form.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
    $errors = [
        'error_key' => 'this is a test'
    ];

    $this->addErrorsToSession($errors);

    return view('resource.create');
}

The message is shown in the view by

error('error_key')
    <p class="text-red-500 text-xs mt-1">{{$message}}</p>    
@enderror

On the initial page load the error message does not appear. Only when I refresh the page the message gets through. How can I get the message to also pop-up on the initial page load?

I am aware that I could return the vie withErrors as

return view('resource.create')->withErrors($errors);

but I would like to have a way to add an error to the session without access to the view.

0

There are 0 answers