Laravel 5.2 : Do something after user has logged in?

风格不统一 提交于 2019-12-19 05:06:30

问题


(I'm a beginner of Laravel)

I'm using Laravel 5.2. I have successfully enabled the Authentication; by doing the php artisan make:auth and stuffs.

So my login is working.

Now i need to do something once someone has logged in. For an simple example:

LOGIN:

  • Once a user has logged in, write a value into Session.
  • For example: $request->session()->put('UserAgent', $ClientUserAgent);

LOGOUT:

  • Same thing to do, once a user has logged out, delete the custom Session value.
  • For example: $request->session()->forget('UserAgent');

I'm not sure whether there are (things like) hooks or Event Listeners, Event Handlers, or something like that.

How can i do it please?


回答1:


For newer versions of Laravel

If you are only doing something very simple then creating an event handler seems overkill to me. Laravel has an empty method included in the AuthenticatesUsers class for this purpose.

Just place the following method inside app\Http\Controllers\LoginController (overriding it):

protected function authenticated(Request $request, $user)
{
    // stuff to do after user logs in
}



回答2:


For the post login, you can do that by modifying App/Http/Controllers/Auth/AuthController.php

Add authenticated() into that class to override the default one:

use Illuminate\Http\Request;

protected function authenticated(Request $request, User $user) {
   // put your thing in here

   return redirect()->intended($this->redirectPath());
}

For the logout, add this function into the same class:

use Auth;

protected function getLogout()
{
    Auth::logout();

    // do something here

    return redirect('/');
}



回答3:


You could try setting up event listeners for the Auth events that are fired.

You can setup a listener that listens for Illuminate\Auth\Events\Login to handle what you need post login and Illuminate\Auth\Events\Logout for post logout.

Laravel Docs - Authentication - Events




回答4:


Alief's Answer below works fine as expected. But as i googled through, using the Event Handlers is probably the more preferred way. (It works like custom hooks).

So without any less respects to Alief's Answer below, let me choose --> this Event Handers approach i just found out.

Thanks all with regards!




回答5:


If you are testing, with authenticated(Request $request, User $user) method dont use alert inside this method to test, it will not show any result, so better put some insert query or something like that to test this method.




回答6:


Why not simple check for

if(Auth::check()){
    //your code
}

Make sure you include use Auth;



来源:https://stackoverflow.com/questions/36491035/laravel-5-2-do-something-after-user-has-logged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!