Make an action after login

2019-09-02 06:24发布

问题:

I have a problem that I want to add a variable to a session after user login (I use Laravel 5 and its auth by artisan make:auth. It looks like this: user->login->give_him_a_key->logout->delete_key. I make a middleware for this but I realize I cannot make middleware run only once when the user does a login, then I go to the file AuthenticateUser.php and add my code in function login. My teacher said that it is not good because I change the code of laravel. He asked me to try to make it without changing the code of laravel.

I tried but cannot find how to catch $request after a user login and make it run only once. I need some guidance.

回答1:

<? php

namespace App\ Http\ Middleware;

use Closure;

class AfterMiddleware {
  public

  function handle($request, Closure $next) {
    $response = $next($request);
    $login_route = "segement1/segement2..";
    $logout_route = "segement1/segement2..";

    if ($request - > is($login_route) && !$request - > session() - > has('key')) {
      $request - > session() - > put('key', 'value');
    }

    if ($request - > is($logout_route) && $request - > session() - > has('key')) {
      $request - > session() - > forget('key');
    }

    return $response;
  }
}

Change routes according to your application



标签: php laravel-5