spatie / laravel-permission

Associate users with roles and permissions
https://spatie.be/docs/laravel-permission
MIT License
12.05k stars 1.76k forks source link

Livewire: teamId is null after a emit/dispatch or wire:init. #2715

Closed vdlindenmark closed 2 weeks ago

vdlindenmark commented 2 weeks ago

Description

We are using the following versions:

Laravel 11.21 Livewire 3.5 Spatie Laravel Permission 6.9 Spatie Laravel Permissions WITH TEAMS

The issue I'm encountering an issue where the teamId is null after a dispatch/emit in Livewire components. This results in checking for permissions returning wrong values (like i'm having no permissions at all).

Steps To Reproduce

  1. Create a Laravel app with Livewire, spatie permissions and teams
  2. Create a Livewire page, and a Livewire component and use the component inside the page.
  3. Add a button to the Livewire component which is only enabled for a specific permission
  4. dispatch a event inside the page, which is listening to inside the component https://livewire.laravel.com/docs/events
  5. The button will now always be disabled, even if you have the permissions. Add a ray(getPermissionsTeamId()) and it will return null...

Another way:

  1. same as above
  2. Create a Livewire page with a public function which logs the teamId
  3. Log the teamId inside the render function, it will be set.
  4. Trigger the function inside the blade of the page
  5. The teamId will be null ...

Example Application

No response

Version of spatie/laravel-permission package:

6.9

Version of laravel/framework package:

11.21

PHP version:

8.2

Database engine and version:

No response

OS: Windows/Mac/Linux version:

No response

drbyte commented 2 weeks ago

Is the session being lost?

vdlindenmark commented 2 weeks ago

No, other pages are still aware of the teamId, just that specific component lost it after a dispatch/emit or wire:init. Lost like, getPermissionsTeamId() is returning null

vdlindenmark commented 2 weeks ago

Looks like it has something to do with a livewire/update call I'm seeing in my console (sail up). A dispatch/emit or wire:init trigger this livewire/update as well

For example: <button wire:click="save" @cannot('update', $vacancy) disabled @endcannot>{{ __('Save') }}</button>

The button is not disabled, so the user has permissions to update a vacancy, but if I check the permissions inside the save function with auth()->user()->cannot('update', $this->vacancy) it is false, logging the teamId results in null 🙃

parallels999 commented 2 weeks ago

@cannot('update', $vacancy)

vdlindenmark commented 2 weeks ago

I finally figured it out. My middleware was wrongly placed. In my own words: It was after the navigation but before the liveware update, or something. So a Livewire update did not know the teamId. Thanks for thinking along!

drbyte commented 2 weeks ago

Yes, that fully makes sense. Thanks for posting back the solution.