Home » Laravel » How to Redirect with Message in Laravel

How to Redirect with Message in Laravel

Redirecting to the previous page after doing an action is common practice in Laravel projects. However, If there is an error while performing the action, you need to inform the user about it. You can return the result in the API response if creating a SPA application. Although, if you have an application rendered using Blade views, session variables are the most frequently used way to transfer messages between pages.

Laravel has methods for placing data in session variables, but you need to implement getting and displaying this data on the next page. In this article, I’ll show you how to make a redirect with a message in Laravel.

Table of Contents

Preparing the testing environment

Let’s create a controller and a blade file with a few buttons to demonstrate how everything works on a simple example project. If you want to test all this on your project, skip this section. I assume you already have Laravel installed. If not, check out this article. In this article, I will provide an example of how to redirect with message in Blade scaffolding generated with the following command:

php artisan ui vue --auth

Create SomeController with three actions: index and success and fail. The first controller action will display the buttons, and the next two will display the error or success messages. Use the following command, to create the controller:

php artisan make:controller SomeController

And paste this code into it:

app/Http/Controllers/SomeController.phppublic function index() { return view("form"); } public function success() { //success } public function fail() { //fail }

Now create a blade view with the form and buttons in resources/views/index.blade.php

resources/views/form.blade.php@extends('layouts.app') @section('content') <div class="card ml-5 mr-5"> <div class="card-body"> <div> <form method="POST" action="{{route('form.success')}}"> @csrf <button type="submit" id="success-button" class="btn btn-success">Test success message</button> </form> </div> <div> <form method="POST" action="{{route('form.fail')}}"> @csrf <button type="submit" id="fail-button" class="btn btn-danger">Test fail message</button> </form> </div> </div> </div> @endsection

And finally, register the routes in routes/web.php:

routes/web.phpRoute::get("/form", [ \App\Http\Controllers\SomeController::class, "index", ])->name("form.index"); Route::post("/success", [ \App\Http\Controllers\SomeController::class, "success", ])->name("form.success"); Route::post("/fail", [ \App\Http\Controllers\SomeController::class, "fail", ])->name("form.fail");

To make sure everything works, open the form page in your browser:

Redirect with message in Laravel

As I said before, the easiest way to pass an info message from one page to another in Laravel is through session variables. In Laravel itself, the @error() Blade helper uses a session to display validation errors for form fields. In short, the session allows you to store client data on the server between requests by identifying this client using a cookie. It works automatically, and you can put or get data from the session using the Session facade or the session() helper. You can read more about interacting with session data in the official documentation.

So that you can store your message, redirect the user to the previous or another page, and then retrieve it on the next page retrieve and display it. Now let’s look at how to display a message on a page using Bootstrap and then how to send it from the controller.

How to display a message in Bootstrap

The Bootstrap framework allows displaying multi-colored alerts by adding an alert class and a color class to the block div containing the message text. Here are some of the available colors:

  • alert-success – green
  • alert-warning – yellow
  • alert-primary – blue
  • alert-danger – red

In this example, I will use the @session() directive to read data from a session in the Blade view. To display messages on all pages, add the alert rendering code to the layout file on which all pages are built. In this case, it is resources/views/layouts/app.blade.php. Here, you can place this code before the main content of the page inside the <main class=”py-4″> tag.

A message about the successful completion of the operation is usually displayed on a green background. The flashing code will look like this:

resources/views/layouts/app.blade.php@if (session()->has('success')) <div class="alert alert-success"> {{ session()->get('success') }} </div> @endif

Here, we check that the session has a success field; if so, it is displayed in a green block. All messages sent with redirect or flash by default are available only for the next request. So, after you go to another page or refresh, this message will no longer exist.

To display the error message, we will use the fail field and red color:

resources/views/layouts/app.blade.php@if (session()->has('fail')) <div class="alert alert-danger"> {{ session()->get('fail') }} </div> @endif

If you want, you can add the same block for a warning message with a yellow background.

How to Redirect with an Info Message

The Blade views are ready to display messages. Now let’s take a look at how to send them. First, look at the flash message example. You can use the session()->flash() method. This method, unlike other methods of working with a session, can flash data only for the next request:

app/Http/Controllers/SomeController.phpsession()->flash("success", "The data has been updated"); return back();

In the above code, the first argument is the session variable name, and the second is the message. If you want to use the with() method in a chain after the redirect() or back() helper, the code will look like this:

app/Http/Controllers/SomeController.phpreturn back()->with("success", "The operation performed successfully");

Or using Laravel redirect back in a chain:

app/Http/Controllers/SomeController.phpreturn redirect()->back()->with("success", "The operation performed successfully");

You can also use the magic method and write the name of the field right after the name of the with() method:

app/Http/Controllers/SomeController.phpreturn back()->withSuccess("The data has been updated");

And the last way is to call the flash method for the Session facade:

app/Http/Controllers/SomeController.phpuse Illuminate\Support\Facades\Session;

app/Http/Controllers/SomeController.phpSession::flash("success", "Changes applied successfully"); return back();

Here is the code for flashing an error message:

app/Http/Controllers/SomeController.phpreturn back()->with("fail", "Failed to perform the operation");

Now you can test the messages in the browser. Just open your browser and click on one of the buttons. Here is how the message about the successful completion of the operation in Bootstrap will look like:

And here is the alert message about failure:

How to Display Notification Using Toastr

Toastr is a JavaScript library that can display notifications in the upper right corner of a web page. You can use it to display your notifications in the same way as you did for Bootstrap. Next, I will show you how to set it up with Vite.

First, you need to install it. Just run the following command:

npm install toastr --save

Next, add the following code to resources/js/app.js to make toastr available on the page:

resources/js/app.jsimport toastr from 'toastr/toastr' window.toastr = toastr;

Add the following line to resources/sass/app.scss to load the CSS styles for toastr:

resources/sass/app.scss@import 'toastr/toastr';

Then you need to rebuild your assets:

npm run build

After this, open resources/views/layouts/app.blade.php and make sure you have app.js and app.scss added there. Usually you don’t need to change anything here:

Next, add the following JavaScript code before the closing tag </body>. For notifications on a green background:

resources/views/layouts/app.blade.php@if(session()->has('success')) <script> document.addEventListener("DOMContentLoaded", function (event) { toastr.success('{{ session()->get('success') }}'); }) </script> @endif

And for error notifications:

resources/views/layouts/app.blade.php@if(session()->has('fail')) <script> document.addEventListener("DOMContentLoaded", function (event) { toastr.error('{{ session()->get('fail') }}'); }) </script> @endif

Finally, you can test it in the browser. The flashed message is shown during a few seconds and then disappears:


This short article explains how to redirect with message in Laravel. As you can see, it is straightforward. In other front-end scaffoldings, the ways of displaying messages may differ, but the approach will be the same.

Leave a Comment

Exit mobile version