I'm making an application, where I've added this to my view-template, to show all the notifications / status-messaged / alerts:
@if ( ! empty( session('notifications') ) )
@foreach( session('notifications') as $notification )
<div class="alert alert-{{ $notification['notification_type'] }}" role="alert">
<strong>{{ $notification['notification_title'] }}</strong> - {{ $notification['notification_message'] }}
</div>
@endforeach
@endif
I'm looking for a way, where I can simply pass a notification to a Collection stored in session('notifications')
, anywhere in my controllers.
But whenever a page is loaded, that session-variable starts out empty. So I would need to both:
- Clear all notifications upon every page load (using
Session::forget('notifications')
I assume, ref). - Instantiate an empty Collection in the session, so I don't need to check-if-empty-and-if-not-then-add-notification-and-if-it-is-empty-then-make-an-empty-collection-and-then-add-the-notification.
Where does code like this belong? I'm fairly new to Laravel, coming from WordPress, where I just would have added an action to init
in functions.php. But where is the equivalent in Laravel?
And is this the proper way of controlling notifications in Laravel? I'm calling it notifications, in lack of better word. Perhaps, 'Alert' or 'Status'? Because I can see that a notification is something related, but still something else.