Laravel Redirect Back with() Message

Published on
2 mins read
––– views

Laravel Redirect Back with() Message

In Laravel, you can use the with method to attach a message to the redirect response when redirecting back. This is commonly used to provide feedback or display a flash message after a certain action.

Here's an example of how you can achieve this in a controller method:

use Illuminate\Support\Facades\Redirect;

public function yourControllerMethod()
{
    // Your logic here

    // Redirect back with a success message
    return Redirect::back()->with('success', 'Your success message goes here');
}

In this example:

  • Redirect::back() is used to create a redirect response to the previous URL.
  • The with method is used to attach the flash message. You can replace 'success' with any key you prefer, and the message string with your desired message.

Displaying the Flash Message

To display the flash message in your view, you can use the session helper or Blade syntax. Here's an example using Blade:

@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

Adjust the HTML and styling according to your needs.

This approach allows you to provide informative messages to users after completing certain actions, enhancing the user experience.