Courses

Roles and Permissions in Laravel 11

The final feature related to the Teams is for the Clinic Owner to choose the current team if they have multiple clinics.

This choice will be visible in the top-right corner of the Laravel Breeze design, like this:

Now, the code.

First, the permission of WHO can change the team? We add a method to the Policy:

app/Policies/TeamPolicy.php

class TeamPolicy
{
// ...
 
public function changeTeam(User $user): bool
{
return $user->hasPermissionTo(Permission::SWITCH_TEAM);
}
}

Next is the Controller method, where we will use that changeTeam immediately. We will add that method into the same TeamController:

app/Http/Controllers/TeamController.php:

use App\Enums\Role;
use Symfony\Component\HttpFoundation\Response;
 
class TeamController extends Controller
{
public function changeCurrentTeam(int $teamId)
{
Gate::authorize('changeTeam', Team::class);
 
$team = auth()->user()->teams()->findOrFail($teamId);
 
if (! auth()->user()->belongsToTeam($team)) {
abort(Response::HTTP_FORBIDDEN);
}
 
// Change team
auth()->user()->update(['current_team_id' => $team->id]);
setPermissionsTeamId($team->id);
auth()->user()->unsetRelation('roles')->unsetRelation('permissions');
 
return redirect(route('dashboard'), Response::HTTP_SEE_OTHER);
}
}

Next, we add the Route for that method.

routes/web.php

Route::middleware('auth')->group(function () {
 
Route::resource('teams', TeamController::class)->only(['index', 'create', 'store']);
Route::get('team/change/{teamId}',
[TeamController::class, 'changeCurrentTeam'])
->name('team.change');
});

Finally, the front-end link to that Route. We just mimic the front-end code of the Profile dropdown...

This lesson is only for Premium Members.
Want to access all lessons of this course?

You also get:

  • 66 courses (1167 lessons, 43 h 18 min total)
  • Premium tutorials
  • Access to repositories
  • Private Discord