Laravel 5 – How to add Flash messages

Today we are going to add flash messages to both our login and logout pages.

Here is what you need to do:

1 – Create a “Partials” folder in your views folder. In the partials folder create 2 files:

“errors.blade.php” and add this code in it:

@if (session()->has('errors'))
{!! session()->get('errors') !!}
@endif

And another file called “success.blade.php” with this code in it:

@if (session()->has('success'))
{!! session()->get('success') !!}
@endif

We are using a fade in effect(animated fadeIn) from Animate.css which you can download freely from the internet(look for it).

2 – Look for the LoginController and add this code:

middleware('guest')->except('logout');
}

protected function authenticated(Request $request, $user)
{
$request->session()->flash('success', 'You are logged in!');
}


public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
$request->session()->flash('errors', 'You are logged out!');
return redirect('/');
}

}

3 – In your app.blade.php file add this code:

@include('partials.errors') @include('partials.success')
@yield('content')

Et voila!

Try to log in and out, the flash messages should now show up on your page.

What did we do?

First we created 2 partial views….but what are they? Partial views are here to stop repeating yourself again and again, you simply pass your message with a status “success or errors” (or whatever you call it) which will automatically guide the script to the correct partial(based on its file name).

Second, we overloaded the original functions authenticated() and logout() and added our flash messages.

Third, we have modified slightly our main app.blade.php file so the partials are included in the layout.

If you have any questions, feel free to ask!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Disclaimer:

As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.