Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ahmed Alaa's avatar

What's the alternative of session for API?

I have a customer auth controller and using Sanctum for authentication

class AuthController extends Controller
{
    use HttpResponses;

    public function login(LoginCustomerRequest $request)
    {
        if (Auth::guard('customer')->attempt(['username' => $request->username, 'password' => $request->password])) {
            $customer = Auth::guard('customer')->user();
            $token = $customer->createToken("customer", ["customer"])->plainTextToken;
            if ($customer->region_id) {
                session(['region_id' => $customer->region_id]);
            }

            return $this->success([
                'customer_id' => $customer->id,
                'token' => $token,
            ], "Customer Logged in Successfully", 200);
        }

        return $this->error([], 'Invalid credentials', 401);
    }
}

and I have a homepage controller that has an index method for homepage preview, it should contain products sold by the vendors around the customer according to his "region_id". I need to tailor the result according to the region_id of logged in customer if exists, I tried using auth()->user()->region_id but it didn't work because I don't use auth middleware in this route to allow unauthenticated users to enter it. then I used session but it didn't work also because I use API, so what's the alternative here?

0 likes
6 replies
jlrdw's avatar

@Ahmed Alaa

I need the unauthenticated user to enter the page

I don't understand. You will need to protect the API data from unauthenticated users.

For signup instructions and API usage instructions, that's where your main website comes in.

1 like
Ahmed Alaa's avatar

@jlrdw It's e commerce website, I want the new users to be able to enter the homepage without authentication, but if he authenticated the displayed products should be tailored according to the customers location

martinbean's avatar

@Ahmed Alaa I think you need to decide whether this is for authenticated users or not. You can’t magically have an endpoint need authentication but also allow guests. It’s one or the other.

If you want to fetch products for an authenticated user, then create a separate endpoint for that (i.e. /me/products) instead.

1 like

Please or to participate in this conversation.