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
Patricia ArquetteOriginal
2024-12-22 16:21:09216browse

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;
    }
}

Registering the Middleware

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

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

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';
}]);

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');

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!

Statement:
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