best way to store error messages in Laravel (session or variable)



PHP Snippet 1:

/*
 * Add an error to Laravel session $errors
 * @author Pavel Lint
 * @param string $key
 * @param string $error_msg
 */
function add_error($error_msg, $key = 'default') {
    $errors = Session::get('errors', new ViewErrorBag);

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

    $bag = $errors->getBags()['default'] ?? new MessageBag;
    $bag->add($key, $error_msg);

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

PHP Snippet 2:

@if ($errors->any())
    <div class="alert alert-danger">
        There were some errors with your request.
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

PHP Snippet 3:

request()->session()->flash('default', 
    request()->session()->get('default', new ViewErrorBag)->put('errors', 
        new MessageBag(['Error message.'])
    )
);