Home >Backend Development >PHP Tutorial >How to Enable CORS in Laravel 5.1 Using Middleware?

How to Enable CORS in Laravel 5.1 Using Middleware?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 08:55:13878browse

How to Enable CORS in Laravel 5.1 Using Middleware?

Enabling CORS in Laravel 5.1

To enable Cross-Origin Resource Sharing (CORS) in Laravel 5.1, you can utilize middleware. Here's a comprehensive guide to implementing CORS using a custom middleware:

  1. Create a CORS Middleware:

Create a file CORS.php in the app/Http/Middleware directory. Add the following code to this file:

<?php

namespace App\Http\Middleware;

use Closure;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin'
        ];
        if ($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
}
  1. Register the Middleware:

In your app/Http/Kernel.php file, add the following code to the $routeMiddleware array:

'cors' => \App\Http\Middleware\CORS::class,
  1. Use the Middleware:

Now you can use the cors middleware in your routes. For example:

Route::get('example', ['middleware' => 'cors', 'uses' => 'ExampleController@dummy']);

By adding these changes, you'll enable CORS for the specified routes and allow cross-origin requests from any domain.

The above is the detailed content of How to Enable CORS in Laravel 5.1 Using Middleware?. 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