Laravel: global variable based on session accessible via ENTIRE application (including tests and policies)

Viewed 182

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.

1 Answers

Generally, information you want to persist during a user's visit is kept in a session variable. You probably will need a step after they log in that allows them to select what account they will be working with unless you want to default them to a favorite or something. The session variable holding the account's ID, for example, will be available everywhere with Laravel's global session function.

You will likely provide a form that submits to a route to change the active account. In that route's method, you can do:

// assign session key to a value
session(['account_id' => $request->input('account_id')]);

then, to access it when in other routes you can do:

// get session key's value
session('account_id')

Refer to this documentation if you need more details: https://laravel.com/docs/7.x/session#using-the-session

Related