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

Generic placeholder image
Brijpal Sharma
laravel  

Date:-May 22nd, 2020 , Posted On:- Web Development


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 http://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' => '[email protected]'));

 

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

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

About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

0 comments

You must be logged in to post a comment.