Laravel Guard讲解

Auth::guard() 用的最多的就是 API 用户登录注册这块了额。

Contract References Facade
Illuminate\Contracts\Auth\Guard Auth::guard()
Illuminate\Contracts\Auth\StatefulGuard ~

访问指定看守器实例-登录

文档

<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\AuthorizationRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthorizationsController extends Controller
{
    // 用户登录
    public function store(AuthorizationRequest $request)
    {
        $username = $request->username;

        filter_var($username, FILTER_VALIDATE_EMAIL) ?
            $credentials['email'] = $username :
            $credentials['phone'] = $username;

        $credentials['password'] = $request->password;

        if (!$token = Auth::guard('api')->attempt($credentials)) {
            return $this->response->errorUnauthorized('用户名或密码错误');
        }

        return $this->respondWithToken($token)->setStatusCode(201);
    }

    // 刷新 token
    public function update()
    {
        $token = Auth::guard('api')->refresh();
        return $this->respondWithToken($token);
    }

    // 删除 token
    public function destroy()
    {
        Auth::guard('api')->logout();
        return $this->response->noContent();
    }

    protected function respondWithToken($token)
    {
        return $this->response->array([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard('api')->factory()->getTTL() * 60,
        ]);
    }
}

代码讲解:

  • $token = Auth::guard('api')->attempt($credentials) // 访问指定看守器实例 相当于【登录】
  • Auth::guard('api')->refresh(); // 在前端实现无感刷新 token, 达到长期登录的目的吧
  • Auth::guard('api')->logout(); // 退出当前登录用户
  • Auth::guard('api')->factory()->getTTL() * 60 // 设置 token 过期的时间

常见用法

1. 为用户生成 token, 通过这个 token 可以获取用户信息

Auth::guard('api')->fromUser($user)

2. 为 token 设置有效期

Auth::guard('api')->factory()->getTTL() * 60

这两个知识点在用户注册的时候将会非常有用。

return $this->response->item($user, new UserTransformer())
            ->setMeta([
                'access_token' => Auth::guard('api')->fromUser($user),  // 为 user 生成 token
                'token_type' => 'Bearer',
                'expires_in' => Auth::guard('api')->factory()->getTTL() * 60, // 设置 60 分钟后过期
            ])
            ->setStatusCode(201);

3. 获取当前登录用户的 id

Auth::guard('api')->id();

3. 获取当前登录用户的 信息

Auth::guard('api')->user();
讨论数量: 0

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!