doudui2229 2017-09-25 13:41
浏览 41
已采纳

流明授权 - 在数组上调用成员函数parameter()

Trying to authorize a user to update a post if the user id and the post user_id matches. I have a custom callback for authorization in the AuthServiceProvider which checks for 'Authorization' header, which is an API key in the boot() function.

$this->app['auth']->viaRequest('api', function ($request) {
            if($request->header('Authorization')) {
                $user = $this->getUserFromAuthorizationHeader($request);

                if (!empty($user)) {
                    $request->request->add(['userid' => $user->id]);
                }

                return $user;
            }
        });

The function getUserFromAuthorizationHeader gets a Request $request parameter and extracts the Authorization header, which is an api key, and then returns a User object.

I defined a gate update-post which checks the user that is returned from the callback and the post passed when calling the gate update-post from a controller.

Gate::define('update-post', function($user, $post){
            Log::info($user);
            return $user->id == $post->user_id;
        });

The way I am calling the Gate in my PostController is by the following

...
$user = $this->getUserFromRequest($request);
        if(Gate::denies('update-post', $post)) {
            return response("Unauthorized.", 401);
        }
...

I logged - using Log:: info() - the $user and $post variables in my Gate and I can successfully see the correct user and post objects being passed, but I get the error Call to a member function parameter() on array and I can't understand why exactly I am getting it.

  • 写回答

1条回答 默认 最新

  • dongtong848825 2017-09-28 09:54
    关注

    You probably need to convert into collection before comparing if you are getting the array like this

    $post = collect($post);
    $user = collect($user);
    Gate::define('update-post', function($user, $post){
                Log::info($user);
                return $user->id == $post->user_id;
            });
    

    Doc Reference

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥20 win11无法启动 持续蓝屏且系统还原失败,无法开启系统保护
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码