doutuzhuohao6449 2017-07-31 20:47
浏览 40

Laravel授权总是返回false

I'm having some problems with Policies on Laravel. The problem is, my create policy always return false, no matter what I do, even when I explicity make it "return true", it will give me 403 forbidden. Its important to mention that I'm making a POST request with axios to my MenuController@store function, then on my store function I'm calling $this->authorize('create') from my Policies...

Take a look:

MenuController@store

public function store(StoreMenuRequest $request, Shop $shop)
{
    $this->authorize('create', [Auth::user(), $shop]);
    $menu = new Menu;

    $menu->name = $request->name;
    $menu->slug = str_slug($menu->name, "-");
    $menu->shop_id = $shop->id;

    $menu->save();

    return $menu->load('items');
}

MenuPolicy

public function create(User $user, Shop $shop)
{
    return $user->owns($shop);
}

* Note that, even when I do "return true" it will not work...

Axios request

addNewMenu()
            {   
                var _this = this;
                axios.post('{{ Route('chef.menus.store', $shop) }}', {
                    name : this.menuName
                }).then(function(response){
                    // Menu saved
                }).catch(function(error){
                    // Errors
                });
            }

No matter what I do, I'll always get false from my create policy. Note that, when I remove my $this->authorize() function from my controller, all works fine, so I suppose that the authorization is the problem, right?

My AuthServiceProvider seems to be okay:

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    'App\Shop' => 'App\Policies\ShopPolicy',
    'App\Menu' => 'App\Policies\MenuPolicy'
];

Can anyone help me figure this out? :( Really appreciate any help. Thank you very much!

**** EDIT ****

For anyone that may be struggling with it, I figured out what was happening, since I'm doing this verification on the MenuPolicy that is linked to a Menu model, and I'm passing a Shop instance to the create() method, I guess that it won't work, I may misunderstood how the poilcy work... So to fix that, I just created a "createMenu()" function inside my Shop policy, this way I can pass a Shop instance to the method and it will work just fine :), cause I just need to verify if the Shop is owned by the current user.

  • 写回答

1条回答 默认 最新

  • down101102 2017-07-31 20:56
    关注

    In Laravel docs there is this example:

    $this->authorize('create',  $shop);
    

    So you shouldn't need to pass in user

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程