Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Clinic Owner: Switching Between Teams

Premium
3:14

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...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (31 h 16 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

M
M ✓ Link copied!

Tip: in the web router when you do the edit/destroy functionality you can change only() to except():

    Route::resource('teams', TeamController::class)->except(['change']);
    Route::get('team/change/{teamId}', [TeamController::class, 'changeCurrentTeam'])->name('team.change');