Flash message after login laravel

2019-02-25 02:30发布

问题:

I'm using Laravel 5.4 with the pre-built auth library.

I would like to have a sweet alert (or popup) come up when a user sucessfully logins but I can't find where the logic is where the redirect to happens.

So:

User logins successfully

Gets forwarded to home controller (need to find this in the code and attach a flash message or something else?)

In my view detect if there's a flash message and make a if there's a flash message in memory so I can then query it with Javascript and show an alert box.

Edit:

I already have this set and it's fine:

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/';

but I need to find where this is referenced? and add a flash message

Thanks

回答1:

That property is referenced in a trait RedirectsUsers in the method redirectPath(). That trait is used in the trait AuthenticatesUsers which is being used in the LoginController.

With that said, what you need to do is fairly simple. In the login controller, we need to override the method in the trait so that it also flashes your message to session. But because that method is in a trait, we don't just want to override it, we still want to use the method in the trait so we first need to alias it as something else.

use AuthenticatesUsers {
    redirectPath as laravelRedirectPath;
};

Now we can safely override this method to flash data to session.

/**
 * Get the post register / login redirect path.
 *
 * @return string
 */
public function redirectPath()
{
    // Do your logic to flash data to session...
    session()->flash('message', 'your message');

    // Return the results of the method we are overriding that we aliased.
    return $this->laravelRedirectPath();
}

If you don't wish to go through this, another thing you can do is listen for the auth.login event and in your handler, flash the data there.



回答2:

  1. Edit your app/Http/Controllers/Auth/LoginController.php to reference the HomeController route and flash your message:

use Session;

protected $redirectTo = '/home'; // add your route here

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
 protected function authenticated(Request $request, $user)
 {
    $request->session()->flash('flash_notification.success', 'Congratulations, you have cracked the code!');
    return redirect()->intended($this->redirectPath());
 }
  1. Then, in your view add the following:

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

  2. Finally, make sure you include bootstrap for the css <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">



回答3:

If you want to have user sign in with ajax and have a flash message on successfully login and then reload/redirect, you will have to make some changes to the Auth\Login Controller

  1. Add this two methods to Auth\Login Controller, this first one will send response on successful login, while the second one will produce error message.

    protected function sendLoginResponse(Request $request) {
        $request->session()->regenerate();
        $this->clearLoginAttempts($request);
        if ($request->ajax()) {
          return response()->json($this->guard()->user(), 200);
        }
        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
     }
    
    protected function sendFailedLoginResponse(Request $request)
    {
        if ($request->ajax()) {
        return response()->json([
            'error' => Lang::get('auth.failed')
        ], 401);
        }
    
        return redirect()->back()
        ->withInput($request->only($this->username(), 'remember'))
        ->withErrors([
            $this->username() => Lang::get('auth.failed'),
        ]);
    } 
    
  2. Then with jQuery (if you are using it), you can do this

    var fdata = $("#loginForm").serialize();
    var furl = $("#loginForm").attr( "action" ); 
    $.ajax({
    url: furl, 
    type: "POST",
    data: fdata,
    success: function(data){
      console.log("Login Success");
      location.reload();
    },
    error: function(data){
      var errors = data.responseJSON;
      if(errors.error){
        console.log(errors.error);
      }
    
    }
    });
    

And of course, if you wish to set custom error/flash message on server you can add it to response json.

Hope it helps.