Support the ongoing development of Laravel.io →
posted 1 year ago
Laravel

I'm building a backend API using Laravel for my web application, and I'm running into issues with CORS (Cross-Origin Resource Sharing) configuration. My front end, built with a different technology stack, is hosted on a separate domain. I've followed numerous guides including https://www.scaler.com/topics/software-engineering/backend-developer-roadmap/ on enabling CORS in Laravel, but I'm still facing problems.

Here's what I've done so far:

In my config/cors.php file, I've set the following configurations:

return [ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['https://myfrontenddomain.com'], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];

I've also tried using middleware to handle CORS in my routes:

`// app/Http/Middleware/EnableCORS.php

namespace App\Http\Middleware;

use Closure;

class EnableCORS { public function handle($request, Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin', 'https://myfrontenddomain.com') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin, Authorization'); } } `

And I've added this middleware to my Kernel.php:

protected $middleware = [ // ... \App\Http\Middleware\EnableCORS::class, ];

Despite these configurations, I'm still encountering CORS-related errors when trying to make requests from my frontend to the Laravel API. Is there something critical I'm missing here? Could anyone provide insights on how to properly set up CORS for a Laravel API that needs to communicate with a frontend hosted on a different domain? Thank you for your help!

Last updated by @jivan84 1 year ago.
0

I am not seeing these:

  1. How do you call api in Laravel? It should start with /api
  2. Which security are you applying on API? I guess you need Sanctum API due to seperate domains or Laravel Passport (if you need OAUTH2). https://laravel.com/docs/10.x/passport#passport-or-sanctum
  3. You cannot call POST without API Security, for example, using Sanctum in Laravel, you need to place middleware('auth:sanctum').

jivan84 liked this reply

1

Thanks for the help.

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Jeevan jivan84 Joined 8 Aug 2023

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.