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

Rainieren's avatar

Laravel - XMLHttpRequest while trying to retrieve data from api call Ajax

I have 2 applications on my system. In one application I store packages and with the other I want to retrieve these package using an ajax api call. In my main project I have this ajax request which is supposed to retrieve data

setInterval(function(){
            $.ajax({
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), 'X-Requested-With': 'XMLHttpRequest'},
                url: 'https://www.rainierlaansite.test/api/packages/get',
                type: 'GET',
                data: {},
                success: function(data) {

                }
            });
        }, 10000);

Do have in mind that I am using valet. The url is local and secured using valet secure.

In my other project I have a route api/packages/get

Route::get('api/packages/get', 'PackagesController@get')->name('get_packages');

Which returns all packages

public function get()
    {
        return Package::all();
    }

But for some reason I get this error:

Access to XMLHttpRequest at 'https://www.rainierlaansite.test/api/packages/get' from origin 'https://rainierlaan.test' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I came across this Stackoverflow post

https://stackoverflow.com/questions/43565877/no-access-control-allow-origin-header-laravel-5-4

which recommended to install barryvdh/laravel-cors. I followed the steps but without any luck. What can this be?

0 likes
1 reply
ismaile's avatar
ismaile
Best Answer
Level 30

@rainieren

It seems like the package is now called: fruitcake/laravel-cors. If you ran: composer require barryvdh/laravel-cors, please remove it with: composer remove barryvdh/laravel-cors

Did you follow precisely these steps for https://www.rainierlaansite.test ?

  • Run composer require fruitcake/laravel-cors
  • Include \Fruitcake\Cors\HandleCors::class, in the $middleware array in app/Http/Kernel.php
  • Run php artisan vendor:publish --tag="cors"
  • Update paths in config/cors.php so that you have 'paths' => ['api/*'],

PS: please keep in mind that there are extra config parameters to add some security. You can start with setting allowed_origins to https://rainierlaan.test. Here you can find more information: https://github.com/fruitcake/laravel-cors#configuration

Please or to participate in this conversation.