Category: Laravel, Laravel, api, api

James Bannister • February 9, 2019 • 3 minute read One of the suggestions that was made was to use the $request object to retrieve the currently authenticated user, rather than relying on auth()->user() or Auth::user() which involves resolving another dependency to retrieve something we already have access to.

By default, web routes are configured to use the web guard and API routes are configured to use the api guard, and unless otherwise specified, Laravel will use the web guard by default.

This works perfectly fine for any of your web routes, as this is what is being used by default: However, when I was refactoring my API controllers, this approach wasn't working so well out of the box: This is because my API routes used the api guard to authenticate, and as I hadn't specified otherwise, $request->user() was trying to resolve the user using the web guard. The fix is fairly simple, just specify the guard you need to use like so: However, this is now the second time you've had to specify that you want to authenticate and retrieve the user using the api guard, because if you are using the auth middleware on your API routes then you may have a controller that looks a little like thi: Wouldn't it be better if we didn't have to repeat this?
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners