How To Solve CORS issue in Laravel and make Laravel CORS Middleware

In this blog post, we make Laravel CORS Middleware solve the issue of CORS.

Sometimes we need backend as a Laravel framework which is run on another port normally it run on //localhost:8000/ and other frontend framework run on another port. then this problem arrives. 

So let’s solve this issue.

Step: 1 Create a Middleware

Create a Middleware into this location App\Http\Middleware

CORS.php 

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

}

Step: 2 Register middleware into Kernel.php

Ok, register Middleware in your app\Http\Kernel.php file like this

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

Step: 3 Route 

Now we can use a route like this.

Route::get('blogs/list', array('middleware' => 'cors', 'uses' => 'BlogController@bloglist'));

Now you can use Laravel API for Vue, Nuxt js, React, or any other Frontend. 

So here we completed a blog post on How To Solve the CORS issue in Laravel and make Laravel CORS Middleware hope it helps you.