tokenCan()方法未定义

huangapple go评论66阅读模式
英文:

tokenCan() method undefined

问题

我目前正在遵循这个教程:

https://nothingworks.netlify.app/blog/laravel-sanctum-multi-auth/

然而,在创建中间件时,tokenCan方法未定义。

我已经安装了Laravel Passport和Sanctum,并确保我的User模型已经调用了use HasApiTokens。请帮我解决问题,谢谢。

英文:

I am currently following this tutorial,

https://nothingworks.netlify.app/blog/laravel-sanctum-multi-auth/

However when creating the middleware, the tokenCan method is undefined.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Laravel\Passport\HasApiTokens;

class CustomerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->user()->tokenCan('role:customer')) {
            return $next($request);
        }

        return response()->json('Not Authorized', 401);

    }
}

I have installed Laravel passport n sanctum, and I have ensured that my User model already calls use HasApiTokens. Please help me out, thank you

答案1

得分: 1

尝试将auth->user()更改为request->user()

原代码:

if (auth()->user()->tokenCan('role:customer')) {
    return $next($request);
}

修改后的代码:

if ($request->user()->tokenCan('role:customer')) {
    return $next($request);
}
英文:

Try to change auth-&gt;user() to request-&gt;user().<br>
From:

  if (auth()-&gt;user()-&gt;tokenCan(&#39;role:customer&#39;)) {
            return $next($request);
        }

To:

if ($request-&gt;user()-&gt;tokenCan(&#39;role:customer&#39;)) {
        return $next($request);
    }

huangapple
  • 本文由 发表于 2023年8月9日 15:27:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定