Handle Laravel Cors via Middleware

2 years ago

If you want to handle Laravel Cors via middleware, here is the way to do that-

First create a file name Cors.php

public function handle($request, Closure $next)
        if ($request->isMethod('OPTIONS')){
            $response = Response::make();
        } else {
            $response = $next($request);
        return $response
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

Then go to http\Kernel.php and added Cors.php file in the middleware route.

protected $middleware = [
    \App\Http\Middleware\Cors::class, //add this line to $middleware variable

If you want to allow other headers to your routes, please add them in the 'Access-Control-Allow-Headers' header field.

Thouhedu Islam Suchi

Thouhedul Islam

Laravel Developer

Hi, I am a Laravel Developer with a passion for web development. I specialize in PHP, particularly Laravel, as well as Javascript, MySql, and other cutting-edge web technologies.

During the day, I work for GLEIF, where I apply my skills and experience to develop innovative web applications. At night, I enjoy contributing to the community and solving problems. You can often find me on Laracasts, where I love to stay active and keep up-to-date with the latest trends in web development.

I am excited about the potential of technology and its power to transform people's lives.