Home » Laravel » How to Send Access-Control-Allow-Origin in Laravel Without a Package

How to Send Access-Control-Allow-Origin in Laravel Without a Package

If you want to send CORS headers to the client depending on the request parameters or settings in the database, you can send them manually. It is not so difficult. First, you need to comment out the default HandleCors middleware in app/Http/Kernel.php, because it overrides CORS headers that are set in the response:

app/Http/Kernel.php//    \Illuminate\Http\Middleware\HandleCors::class

If you want to send the Access-Control-Allow-Origin header with a specific origin to the current user, create a response using the response() helper and use withHeaders() to send the Access-Control-Allow-Origin header. For example, haait.net:

routes/api.phpRoute::get("/first", function () {     $response = response()->json([         "status" => "ok"     ]);     $response->withHeaders([         "Access-Control-Allow-Origin" => "https://haait.net",     ]);     return $response; });

Also, you can send the current origin if it matches a specific pattern:

routes/api.phpRoute::get("/second", function (\Illuminate\Http\Request $request) {     $response = response()->json([         "status" => "ok"     ]);     $origin = $request->headers->get("Origin");     if (\Str::endsWith($origin, "haait.net")) {         $response->withHeaders([             "Access-Control-Allow-Origin" => "https://haait.net",         ]);     }     return $response; });

You can check headers using the developer console in your browser or the curl command.

Leave a Comment