How would I do a middleware to catch the user if there is a token and if it does not have a token, to continue without blocking the request?

Posted 9 months ago by valdinei.lima

Hello everyone, I have a "domain.com/v1/campaigns" route that returns a list of data. This route does not need to have a token to access. But if there is a token entered in the header, I'd like to return the user's data. I can not use the "auth: api" middleware because it would make the route always require a token, and that would not be the case. The token on this route would be optional. How would I do a middleware to catch the user if there is a token and if it does not have a token, to continue without blocking the request?

Imagine the situation... I have this route:

ROUTE

$router->get('campaign/{slug?}', [
    'uses' => '[email protected]'
]);

This route is public, ie it is not necessary to inform a token in order to list the items. However, if the user is connected, every time he accesses the route, a token is added to the header (Bearer XYZZYZXZ...)

In the controller, I need to get the user's model if there is a token informed, but I can not.

CONTROLLER

class ControllerPublic extends ApiController
{
    public function getCampaign($slug)
    {

        // THERE IS NO TOKEN IN THE HEADER PRINT USER //
        if (auth()->check()) {
            dd(auth()->user()->toArray());
        }

        $data = $this->call(GetCampaignPublicAction::class, [$slug]);
        return $this->transform($data, CampaignTransformer::class);
    }
}

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.