Skip to content
Advertisement

Laravel api route that grabs Auth::user() when Authorization is sent, but doesn’t hit 401 whenever you don’t

So right now I’m using Laravel’s default auth for api routes by doing this:

JavaScript

The only thing with this is that it will throw a 401 if a non logged in user hits that page.

What I’m wondering is if there’s a way to have a route that will login the user if a token is sent, but if not, they can still hit the api.

I know this will most likely be a custom Middleware, but I don’t have a lot of experience with creating Middlewares so I’m not really sure where to start

EDIT

app/Http/Kernel.php

JavaScript

Here’s a pretty simplified version of my routes api.php file routes/api.php

JavaScript

Basically I’m wanting the ability to hit the /leagues/{id} route with either a logged in user or a non logged in user. And if the user is logged in grab the user via Auth::user(). If it helps at all, I’m using React for a front end and sending an api_token in the Authorization header like Bearer $token.

Advertisement

Answer

I figured out a way by creating my own custom Middleware. For anyone interested, here it is:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement