🔥 Flash Messages with Sweetalert— Laravel

Kodeas
2 min readJun 21, 2020

--

When a user took an action, we all love to show them a success message or error message. I actually like to use sweet-alert as it looks professional.

Wouldn’t it be cool if we could simply write in our controllers:

$this->flashSuccess("Task was successful!");$this->flashError("Task failed!");

…don’t actually need to do anything in the front-end side every time?

Show me how:

Laravel lets us easily achieve this by using Session Flash Data:

$request->session()->flash('status', 'Task was successful!');

That’s cool… but how to use it easily, in a more reusable way?

I let my base Controller to implement this logic so that I can access it anywhere I want.

class Controller extends BaseController
{
public function
flashSuccess($message) {
$this->setupFlash("Operation Successful", $message, 'success');
}

public function flashError($message) {
$this->setupFlash("Something went wrong", $message, 'error');
}

private function setupFlash($title, $message, $type) {
request()->session()->flash('swal_msg', [
'title' => $title,
'message' => $message,
'type' => $type,
]);
}
}

(Though, for making it tidier, I prefer to separate this into its own trait and use FlashMessage; trait in my base Controller)

For handling the front-end of this implementation, I like to a separate blade file to hold this partial called “flash-swal.blade.php”.

@if (session()->has('swal_msg'))
<script>
notification = @json(session()->pull("swal_msg"));
swal(notification.title, notification.message, notification.type);<!--
To prevent showing the notification when on browser back
we can do:
-->
@php
session()->forget('swal_msg');
@endphp
</script>
@endif

And then in my “layout blade”:

@include('partials.flash-swal')

The usage:

Really dummy usage example can be:

PostsController extends Controller
{
public function store(Post $post)
{
if ($post->owner->id != auth()->user()->id) {
$this->flashError("You are not the owner");
return redirect()->back();
}
$this->flashSuccess("Post edited successfully"); return redirect()->back();
}
}

And you don’t need to do anything on the front-end side after adding your flash-swal partial blade into you layout blade.

--

--