Easiest Way to Allow CORS in Laravel 6 or Any Version
In this tutorial, I’m going to share how to allow Cross-Origin Resource Sharing (CORS) in Laravel 6 or any version of Laravel.
According to Wikipedia: Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
We can allow CORS in many ways in Laravel. Let’s solve the issue by following the easiest way.
The Easiest Solution
Go to bootstrap
folder and open app.php
file. Then just add these lines at the top of the file.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
Another Solution
Run this artisan command:
php artisan make:middleware Cors
Now open Cors.php from App\Http\Middleware
folder and replace handle()
function with this code:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorizations');
}
Lastly, open Kernel.php from App\Http
folder add the below line to the $middleware
array:
protected $middleware = [
...
\App\Http\Middleware\Cors::class,
];
Now run the application and call API from anywhere.
The tutorial is over. Thank you. ?Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)