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

Laracast13's avatar

API IP protection

Hello, In Laravel, I have an API. I'm currently utilizing this API on "website 2". How can I ensure that the API only accepts requests from the IP address of "website 2"?

I tried


        if ($request->ip() !== $allowedIP) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

but $request->ip() gives user ip not server

0 likes
2 replies
Shivamyadav's avatar

try using this

$allowedIP = 'your_website2_ip';

if ($_SERVER['SERVER_ADDR'] !== $allowedIP) {
    return response()->json(['error' => 'Unauthorized'], 401);
}

JussiMannisto's avatar

but $request->ip() gives user ip not server

What do you mean by this? If the request comes from website 2, then $request->ip() returns its IP. Your code is fine.

Please or to participate in this conversation.