How to Enable Cors with Laravel 5

Laravel 5 Middleware

By default, cors requests are not enabled with any PHP farameworks. You should enable it if you need to use cors request.

Even, you can enable cors request, i strongly suggest you yo use a proxy server. Accept requests from your proxy server,  pass it to your application server, don’t let any other client make any http request from your application server.

Here is how to enable CORS with Laravel 5 PHP framework:

1. Create CORS Middleware

To initialize middleware class you should use artisan command line tool.

php artisan make:middleware Cors

This command will create the Cors.php file at /app/Http/Middleware

You should edit, Cors.php 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)
    {

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

2. Register Middleware

To use your middleware in your project you should register middleware class into your project. To register your middleware you should edit /app/Http/Kernel.php file.

In the end of the file you should see $routeMiddleware array. That is object we should add our middleware. We will update routeMiddleware like this:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'cors' => \App\Http\Middleware\Cors::class,
    ];

We game ‘cors’ name to our middleware. Now Laravel will load our middleware but won’t use it until we put it in routes.

3. Make Your Routes Use CORS Middleware

You have options when you want to make your routes use your middleware.  I usually prefer to create route groups that uses same middleware. But sometimes you need to use Route::get()->middleware([middlewares]) That is the way how you can assign middleware to only one route.

Here is my favourite way to call middleware:

Route::group(['middleware' => ['cors']], function()
{
    Route::post('api/v1/blood/add', 'BloodController@addPost');

    Route::post('api/v1/vote/add', 'VoteController@addVotePost');
});

 

4. Done!

You’ve done for today.

 

Leave a Reply

Your email address will not be published. Required fields are marked *