Home > Backend Development > PHP Tutorial > How to Implement Custom CORS Middleware in Laravel 5.1?

How to Implement Custom CORS Middleware in Laravel 5.1?

Patricia Arquette
Release: 2024-12-22 16:21:09
Original
213 people have browsed it

How to Implement Custom CORS Middleware in Laravel 5.1?

Enabling CORS in Laravel 5.1

When developing APIs with Laravel 5.1, enabling Cross-Origin Resource Sharing (CORS) is crucial for allowing requests from different origins. While various CORS libraries exist, this article focuses on a custom middleware implementation specifically tailored for Laravel 5.1.

Middleware for CORS

To enable CORS, create a middleware class in app/Http/Middleware/CORS.php:

use Closure;

class CORS {
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");
        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin'
        ];
        if ($request->getMethod() == "OPTIONS") {
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value) {
            $response->header($key, $value);
        }
        return $response;
    }
}
Copy after login

Registering the Middleware

Register your middleware in the app/Http/Kernel.php:

protected $routeMiddleware = [
    'cors' => 'App\Http\Middleware\CORS',
];
Copy after login

Using the Middleware

To use CORS middleware in a route, add 'middleware' => 'cors' to the route definition:

Route::get('example', ['middleware' => 'cors', function () {
    return 'example';
}]);
Copy after login

Laravel ^8.0 Update

In Laravel versions 8.0 and above, you need to import the controller namespace and use the class name like this:

use App\Http\Controllers\ExampleController;

Route::get('example', [ExampleController::class, 'dummy'])->middleware('cors');
Copy after login

By following these steps, you can effortlessly enable CORS in your Laravel 5.1 API, allowing requests from different domains and providing a secure and flexible API environment.

The above is the detailed content of How to Implement Custom CORS Middleware in Laravel 5.1?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template