In this episode, we tackle the annoyance of always having to write request()->user()->currentTeam
everywhere in our Laravel code. Instead, we're building a convenient shortcut to access the current team more cleanly.
First, we use Laravel's macroable trait to add a team()
method directly onto the Request object. This way, you can just write request()->team
and instantly get the currently authenticated user's team. We do this by editing our AppServiceProvider
and adding a macro.
We also write tests to make sure our new helper works. We bump into a little roadblock with authentication in tests, so we check out how to set the user on the request object properly for testing purposes. Along the way, we also ensure our macro returns null
if no user is authenticated, and we show both a defensive if
statement and the null-safe operator as options.
Then, we take it a step further and add a global team()
helper function by creating a helpers.php
file, registering it in composer.json
, and reloading Composer. Now, you can just call team()
anywhere in your app to get the currently authenticated team, making your code much cleaner and more expressive.
Finally, we write tests for the helper, ensuring it behaves the way we expect.
So, after this episode, you can get the current team super easily, either with request()->team
or just the team()
helper, all throughout your Laravel app!