tokenCan() 方法未定义

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

tokenCan() method undefined

问题

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

英文:

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.

&lt;?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()-&gt;user()-&gt;tokenCan(&#39;role:customer&#39;)) {
            return $next($request);
        }

        return response()-&gt;json(&#39;Not Authorized&#39;, 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()。<br>
从:

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-2.html
匿名

发表评论

匿名网友

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

确定