How to Allow Specific Origins with Laravel Cors
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Here is the table of contents for Laravel articles
This article summarizes how to allow specific origins with Laravel Cors.
When operating Laravel with an API, if you do not allow the origin that hosts what you created on the front end,
Access to fetch at 'https://127:0.0.1:8000/api/user' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Such an error occurs.
The content is about resolving it.
Operating environment
Laravel6
Laravel8
It is a little different between 6 and 8.
Conclusion
In Laravel6, install the package with the following command.
It is not necessary for Laravel8. It is already included.
Command
composer require fruitcake/laravel-cors
php artisan vendor:publish --tag="cors"
app/Http/Kernel.php
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
// ...
];
Add one line.
This is only for Laravel6. The same applies to Laravel8 below.
config/cors.php
To allow specific origins, modify the origin item in this file.
The initial setting is "*", which means all are allowed.
'allowed_origins' => ['https://****.com'],
I modified it like this. This time, I allow the origin operating on the front end.
Since I modified the config file,
php artisan config:cache
or php artisan config:clear
Do.
The configuration is now complete.
Summary
That's all.
I created this article hoping that it would be helpful if there is an article that can solve errors and Laravel.
I would be grateful if it helps someone.
For complaints or feedback, please contact me via Twitter.
Popular Articles
Deploying a PHP7.4 + Laravel6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs