tokenCan() 方法未定义

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

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.

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Laravel\Passport\HasApiTokens;
  6. class CustomerMiddleware
  7. {
  8. /**
  9. * Handle an incoming request.
  10. *
  11. * @param \Illuminate\Http\Request $request
  12. * @param \Closure $next
  13. * @return mixed
  14. */
  15. public function handle($request, Closure $next)
  16. {
  17. if (auth()->user()->tokenCan('role:customer')) {
  18. return $next($request);
  19. }
  20. return response()->json('Not Authorized', 401);
  21. }
  22. }

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.

  1. &lt;?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Http\Request;
  5. use Laravel\Passport\HasApiTokens;
  6. class CustomerMiddleware
  7. {
  8. /**
  9. * Handle an incoming request.
  10. *
  11. * @param \Illuminate\Http\Request $request
  12. * @param \Closure $next
  13. * @return mixed
  14. */
  15. public function handle($request, Closure $next)
  16. {
  17. if (auth()-&gt;user()-&gt;tokenCan(&#39;role:customer&#39;)) {
  18. return $next($request);
  19. }
  20. return response()-&gt;json(&#39;Not Authorized&#39;, 401);
  21. }
  22. }

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>
从:

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

到:

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

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

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

To:

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

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:

确定