222

I am trying to redirect to the previous page with a message when there is a fatal error.

App::fatal(function($exception)
{
    return Redirect::back()->with('msg', 'The Message');
}

In the view trying to access the msg with

Sessions::get('msg')

But nothing is getting rendered, am I doing something wrong here?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
M T
  • 4,099
  • 4
  • 21
  • 27

25 Answers25

343

Try

return Redirect::back()->withErrors(['msg' => 'The Message']);

and inside your view call this

@if($errors->any())
<h4>{{$errors->first()}}</h4>
@endif
STA
  • 30,729
  • 8
  • 45
  • 59
giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
195

Laravel 5 and later

Controller

 return redirect()->back()->with('success', 'your message,here');   

Blade:

@if (\Session::has('success'))
    <div class="alert alert-success">
        <ul>
            <li>{!! \Session::get('success') !!}</li>
        </ul>
    </div>
@endif
Ketan Akbari
  • 10,837
  • 5
  • 31
  • 51
  • 7
    Array to string conversion :( – Yevgeniy Afanasyev Jun 15 '18 at 03:58
  • Comment left as edit: If it gives Error : Array to String Conversion, then just small fix in **controller** `return redirect()->back()->with('success', 'your message here');` – Michael Aug 01 '19 at 02:15
  • @Michael What do you mean if? It definitely returns an array! – Andrew Savetchuk Aug 01 '19 at 09:35
  • @AndrewSavetchuk -- it isn't my comment. Another SO user had edited the answer when he should just have left a comment here or created his own answer. – Michael Aug 01 '19 at 09:37
  • @Michael we should edit the answer in the right way because if you run that code it won't work. – Andrew Savetchuk Aug 01 '19 at 09:41
  • @AndrewSavetchuk Not according to [meta StackOverflow](https://meta.stackoverflow.com/questions/260245/when-should-i-make-edits-to-code) leave a comment instead or make a correct answer. – Michael Aug 01 '19 at 09:43
  • Fixed! Now it returns a string. Enjoy – Gediminas Šukys May 27 '20 at 06:09
  • we have session() and cookie() helpers to use in your blade files instead of Facades I don't know why lot of people don't like helpers. – Amir Hassan Azimi Mar 02 '22 at 16:31
  • 1
    This one worked in Laravel 9. In controller I have used: return redirect()->back()->with('message', 'Quantity Constraint Failed'); Inside blade of redirected location, I put @if(session()->has('message'))

    {{session('message')}}

    @endif
    – Rajib May 30 '22 at 08:03
  • 1
    @Rajib thanks, I used your code and it worked perfectly for me. – Vic Iyke Jun 26 '22 at 23:27
79

Alternative approach would be

Controller

use Session;
       
Session::flash('message', "Special message goes here");
return Redirect::back();

View

@if (Session::has('message'))
   <div class="alert alert-info">{{ Session::get('message') }}</div>
@endif
vimuth
  • 5,064
  • 33
  • 79
  • 116
Rick
  • 12,606
  • 2
  • 43
  • 41
28

In Laravel 5.4 the following worked for me:

return back()->withErrors(['field_name' => ['Your custom message here.']]);
haakym
  • 12,050
  • 12
  • 70
  • 98
  • Hi. The accepted answer is for use in Laravel 4 (see the question tag), the parameters for the `withErrors()` method in the answer is an array with two elements: `['msg', 'The Message']`. See the api for acceptable parameters: https://laravel.com/api/4.2/Illuminate/Http/RedirectResponse.html#method_withErrors – haakym May 08 '17 at 17:04
  • In my answer, for use in Laravel 5.4, the parameters for the `withErrors()` method is an array with one element that is a `key => value` pair, where the value is an array. 5.4 API: https://laravel.com/api/5.4/Illuminate/Http/RedirectResponse.html#method_withErrors – haakym May 08 '17 at 17:05
13

You have an error (misspelling):

Sessions::get('msg')// an extra 's' on end

Should be:

Session::get('msg')

I think, now it should work, it does for me.

bumerang
  • 1,776
  • 21
  • 30
12

Just set the flash message and redirect to back from your controller functiion.

    session()->flash('msg', 'Successfully done the operation.');
    return redirect()->back();

And then you can get the message in the view blade file.

   {!! Session::has('msg') ? Session::get("msg") : '' !!}
Majbah Habib
  • 8,058
  • 3
  • 36
  • 38
  • 2
    I think `{!! Session::get("msg", '') !!}` should be enough. `get()` already checks if the _key_ exists and returns the default value otherwise. – Emile Bergeron Oct 03 '17 at 22:24
11

In Laravel 5.5:

return back()->withErrors($arrayWithErrors);

In the view using Blade:

@if($errors->has())
    <ul>
    @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif
Sergio
  • 317
  • 1
  • 7
  • 18
9

For Laravel 5.5+

Controller:

return redirect()->back()->with('success', 'your message here');

Blade:

@if (Session::has('success'))
    <div class="alert alert-success">
        <ul>
            <li>{{ Session::get('success') }}</li>
        </ul>
    </div>
@endif
Andrew Savetchuk
  • 1,552
  • 1
  • 16
  • 21
8

In laravel 5.8 you can do the following:

return redirect()->back()->withErrors(['name' => 'The name is required']);

and in blade:

@error('name')
<p>{{ $message }}</p>
@enderror
justijn
  • 139
  • 1
  • 10
5

in controller

For example

return redirect('login')->with('message',$message);

in blade file The message will store in session not in variable.

For example

@if(session('message'))
{{ session('message') }}
@endif
Hatim Hussein
  • 117
  • 1
  • 4
5

I know this is an old post but this answer might help somebody out there.

In Laravel 8.x this is what worked for me: You can return the error to the previous page or to another page.

return Redirect::back()->withErrors(['password' => ['Invalid Username or Password']]);

This will also work:

return view('auth.login')->withErrors(['username' => ['Invalid Username or Password']]);

Please ENSURE, however, that the page/view you are returning has a field name that corresponds to the first parameter passed in the withErrors method (in this case, username or password) and that the @error directive in your view references the same field like this

@error('password') //or @error('username')
 <span class="invalid-feedback" role="alert">
   <strong>{{ $message }}</strong>
 </span>
@enderror 

for example

Hope this helps somebody. Cheers.

Cedric
  • 45
  • 1
  • 4
5

#Laravel-9 Inside the blade where this redirection back action initiated

   return redirect()->back()->with('message', "The Message");            

Inside the blade where this form, will be returned after the above action

                @if(session()->has('message'))
                <p class="alert alert-success"> {{ session()->get('message') }}</p>
                @endif
Rajib
  • 392
  • 4
  • 16
4

I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:

Pull in the package through Composer.

"require": {
  "laracasts/flash": "~1.0"
}

Include the service provider within app/config/app.php.

'providers' => [
  'Laracasts\Flash\FlashServiceProvider'
];

Add a facade alias to this same file at the bottom:

'aliases' => [
  'Flash' => 'Laracasts\Flash\Flash'
];

Pull the HTML into the view:

@include('flash::message') 

There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.

optional changes:

If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:

@if (Session::has('flash_notification.message'))
  <div class="{{ Session::get('flash_notification.level') }}">
    {{ Session::get('flash_notification.message') }}
  </div>
@endif

If you would like to view the HTML pulled in by @include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.

If you need to modify the partials do:

php artisan view:publish laracasts/flash

The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.

DutGRIFF
  • 5,103
  • 1
  • 33
  • 42
4

Here is the 100% solution

*Above mentioned solutions does not works for me but this one works for me in laravel 5.8:

$status = 'Successfully Done';
return back()->with(['status' => $status]);

and receive it as:

@if(session()->has('status'))
     <p class="alert alert-success">{{session('status')}}</p>
@endif
Imran_Developer
  • 343
  • 5
  • 13
  • The solution will work perfectly with 5.8 just try doing it like this. **Controller** return back()->withErrors(['yourfieldname' => 'yourerrormsg.']); **Blade** @error('email') {{ $message }} @enderror – Mudit Gulgulia Dec 26 '20 at 09:05
4

It works for me and Laravel version is ^7.0

on Controller

return back()->with('success', 'Succesfully Added');

on Blade file

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

For documentation look at Laravel doc

Ani
  • 551
  • 1
  • 5
  • 18
3

For laravel 5.6.*

While trying some of the provided answers in Laravel 5.6.*, it's clear there has been some improvements which I am going to post here to make things easy for those that could not find a solution with the rest of the answers.

STEP 1:

Go to your Controller File and Add this before the class:

use Illuminate\Support\Facades\Redirect;

STEP 2: Add this where you want to return the redirect.

 return Redirect()->back()->with(['message' => 'The Message']);

STEP 3: Go to your blade file and edit as follows

@if (Session::has('message'))
<div class="alert alert-error>{{Session::get('message')}}</div>
 @endif

Then test and thank me later.

This should work with laravel 5.6.* and possibly 5.7.*

Akintunde
  • 3,525
  • 1
  • 21
  • 23
3

In blade

 @if(Session::has('success'))

    <div class="alert alert-success" id="alert">
        <strong>Success:</strong> {{Session::get('success')}}
    </div>

@elseif(session('error'))
    <div class="alert alert-danger" id="alert">
        
        <strong>Error:</strong>{{Session::get('error')}}
    </div>
@endif

In controller for success

 return redirect()->route('homee')->with('success','Successfully Log in '); 

for error

 return back()->with('error',"You are not able to access");
Ricky
  • 31
  • 3
2

I faced with the same problem and this worked.

Controller

return Redirect::back()->withInput()->withErrors(array('user_name' => $message));

View

<div>{{{ $errors->first('user_name') }}}</div>
A. Mitani
  • 21
  • 2
2

laravl 8

Route::post('/user/profile', function () {
// Update the user's profile...

return redirect('/dashboard')->with('status', 'Profile updated!');
});

Blade syntax

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

enter link description here

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 08 '22 at 06:19
  • Not working on laravel 9. am i missing something – Rajib May 31 '22 at 03:59
1

For Laravel 3

Just a heads up on @giannis christofakis answer; for anyone using Laravel 3 replace

return Redirect::back()->withErrors(['msg', 'The Message']);

with:

return Redirect::back()->with_errors(['msg', 'The Message']);
Dev1997
  • 657
  • 1
  • 5
  • 16
1

Laravel 5.6.*

Controller

if(true) {
   $msg = [
        'message' => 'Some Message!',
       ];

   return redirect()->route('home')->with($msg);
} else {
  $msg = [
       'error' => 'Some error!',
  ];
  return redirect()->route('welcome')->with($msg);
}

Blade Template

  @if (Session::has('message'))
       <div class="alert alert-success" role="alert">
           {{Session::get('message')}}
       </div>
  @elseif (Session::has('error'))
       <div class="alert alert-warning" role="alert">
           {{Session::get('error')}}
       </div>
  @endif

Enyoj

The Bumpaster
  • 944
  • 7
  • 20
0

I got this message when I tried to redirect as:

public function validateLogin(LoginRequest $request){
    //

    return redirect()->route('sesion.iniciar')
            ->withErrors($request)
            ->withInput();

When the right way is:

public function validateLogin(LoginRequest $request){
    //

    return redirect()->route('sesion.iniciar')
            ->withErrors($request->messages())
            ->withInput();
manix
  • 14,537
  • 11
  • 70
  • 107
0

Laravel 5.8

Controller

return back()->with('error', 'Incorrect username or password.');

Blade

  @if (Session::has('error'))
       <div class="alert alert-warning" role="alert">
           {{Session::get('error')}}
       </div>
  @endif
wobsoriano
  • 12,348
  • 24
  • 92
  • 162
0
    **Try This**
    
    Try This Code 
    --- Controller ---

    return redirect('list')->with('message', 'Successfully');
    return redirect('list');
   
  ----  Blade view ------
    @if(session()->has('message'))
        <div class="alert alert-success">
            {{ session()->get('message') }}
        </div>
    @endif
0

As of laravel 9.19, If you use Session::flush(), It will delete all of your session data so you should use Session::put().

use Illuminate\Support\Facades\Session;
Session::put('msg', 'The Message');

If you want to store the data in an array use,
Session::push('msg','The message'); This will return an array in your view. 

You can now access the session data in your view with the session() helper function. In your case that will be:

session('msg')