Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 redirect back with success message

I'm trying to get a success message back to my home page on laravel.

return redirect()->back()->withSuccess('IT WORKS!'); 

For some reason the variable $success doesn't get any value after running this code.

The code I'm using to display the succes message:

@if (!empty($success))     <h1>{{$success}}</h1> @endif 

I have added the home and newsletter page to the web middleware group in routes.php like this:

Route::group(['middleware' => 'web'], function () {     Route::auth();      Route::get('/', function () {         return view('home');     });      Route::post('/newsletter/subscribe','NewsletterController@subscribe'); }); 

Does anyone have any idea why this doesn't seem to work?

like image 974
Stefan Avatar asked May 22 '16 15:05

Stefan


People also ask

Can we send data with redirect in laravel?

Redirect with Data Firstly, you can just use with(): return redirect()->back()->with('error', 'Something went wrong. '); This code will add an item to the Session Flash Data, with key "error" and value "Something went wrong" - and then you can use that in the result Controller or View as session('error').


1 Answers

You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.

If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:

return redirect()->back()->with('message', 'IT WORKS!'); 

Displaying message if it exists:

@if(session()->has('message'))     <div class="alert alert-success">         {{ session()->get('message') }}     </div> @endif 
like image 150
Alexey Mezenin Avatar answered Sep 22 '22 15:09

Alexey Mezenin