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

aneeskodappana's avatar

Access-Control-Allow-Origin in Laravel 5.4

how to implement Access-Control-Allow-Origin in laravel 5.4, the middleware way of adding with Cors is not working on laravel 5.4.

I have to post requests to API routes using angular http.post or get, but the console showing the following error {XMLHttpRequest cannot load http://tester.ionic/api/smsBalance/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.}

i solved the issue by adding the following code to index.php inside the public folder

    header("Access-Control-Allow-Origin: http://localhost");

is there any better way to do it ( in a laravel way)

0 likes
10 replies
cdiazr's avatar

I installed Laravel Cors by Barryvdh v0.9.2 but just one of my routes into api.php is working.

API is allowing any type of request

I'm getting this following error just with some routes:

"Blocked cross-source request: The same source policy does not allow the reading of remote resources at http://app.shop/api/v1/categories/. (Reason: CORS 'Access-Control-Allow-Origin' header not present)"

I'm sharing my cors.php config file

return [
    /*
    |--------------------------------------------------------------------------
    | Laravel CORS
    |--------------------------------------------------------------------------
    |
    | allowedOrigins, allowedHeaders and allowedMethods can be set to   array('*') to accept any value.
    |
    */

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [''],
    'maxAge' => 0,
];
spekkionu's avatar

Can you try looking at the headers for the response when you run a request to the api? Does it include the Access-Control-Allow-Origin header?

You can try running the request with curl -I url-to-request to just get the headers for the response.

Might seem like some silly questions but did you install the cors package on the application with the api or the application making the requests? Did you remember to register the package service provider when you installed it? Did you add the middleware to your api group or just a single api route (the one that is working)?

cdiazr's avatar

It's ok man, you have to be sure everything is well installed. I install cors package following all the steps from Barryvdh and everything is registered properly:

      protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \Barryvdh\Cors\HandleCors::class
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
        \Barryvdh\Cors\HandleCors::class,
    ],
];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'cors' => \Barryvdh\Cors\HandleCors::class,
];

Next is a screenshot of curl response: http://prntscr.com/fr31yk

spekkionu's avatar

Maybe try adding some debug code or running a request with step debugging with xdebug to see if the middleware is running.

If it is maybe IIS is stripping out the header? There might be some cors related settings in IIS for the site. I haven't used IIS in a few years so I'm not too familiar with what the settings look like now.

IshanMahajan's avatar

Just place in your bootstrap/app.php <?php header('Access-Control-Allow-Origin: *'); ?> For development only not in production

2 likes
saidbakr's avatar

@IshanMahajan It is the best and the simplest answer. I have a simple controller's action that does not use view, it just returns a JSON object like the following, and just adding the header function with the specified parameters, solved the problem:

public function timeNow()
    {
        header('Access-Control-Allow-Origin: *');
        return ['time' => date('H:i:s'), 'uTime' => time()];
    }
2 likes
jadrenko's avatar

Using the Response Factory you can use something like this

public function actionName()
{
    return response()->json(['success' => true], 200, [
        'Access-Control-Allow-Origin' => 'http://localhost'
    ]);
}

Please or to participate in this conversation.