Search code examples
phplaravellaravel-5.3

Enable Corrs in laravel 5.3


I tried to enable Cors in laravel 5.3. But it don't run.
I have tried many ways.
First, I tried to include middleware Cors and add to Kernel.php.

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

Then, I used plugin barryvdh/laravel-cors but don't run.

Hopefully, someone will guide me or correct me.


Solution

  • As from the example on https://laravel.com/docs/5.4/middleware

    However, this middleware would perform its task after the request is handled by the application:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class AfterMiddleware
    {
        public function handle($request, Closure $next)
        {
            $response = $next($request);
    
            // Perform action
    
            $response->header('Access-Control-Allow-Origin', '*');
    
            return $response;
        }
    }
    

    In short: add it to the response, not to the request