My application allows users to be apart of different accounts. On each account, they may have varying roles. I essentially want to do what Mailchimp does.
A user can be the "owner" of one account, while only an author on another.
But if I'm logged as a user who's an owner on one account, and then I want to "switch accounts", how can I handle this change in the application?
Currently I'm grabbing the user's first account model
auth()->user()->accounts()->first
If I want to allow them to switch to another account, how can I globally handle this and remember their choice across the application and every route.
I understand how to grab a specific model like Account::find($id), but this needs to be global and then in every controller I need to reference currentAccount somehow.
Edit:
So I have a good idea on how to actually manage the account ID via sessions. I put together some very simple logic on setting the current account based on session data. I just put this on a controller route and returned the data for testing:
public function getCurrentAccount(Request $request) {
$request->session()->put('account_id', 3);
$account_id = $request->session()->get('account_id');
$user = auth()->user();
if ($account_id) {
$account = Account::findOrFail($account_id);
if ($user->accounts->contains($account->id)) {
$this->account = $account;
} else {
dd('error');
}
} else {
$this->account = auth()->user()->accounts()->first();
}
return $this->account;
}
So the above is the basic logic I need to apply. simple enough. However, I don't really know WHERE to put the initial session value.
And then I need to make a variable based on the session data accessible to all controllers, views, policies / authorization, tests, etc.