user3159043
user3159043

Reputation: 317

Laravel authorize always returns 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.

Upvotes: 0

Views: 1987

Answers (1)

user3743266
user3743266

Reputation: 1172

In Laravel docs there is this example:

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

So you shouldn't need to pass in user

Upvotes: 0

Related Questions