Enable CORS in Laravel Application

In this post, we will explain what cross-origin resource sharing (CORS) is and how to enable CORS for Laravel applications.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. Generally, assets like images, stylesheets, and scripts can be easily embedded into web pages. CORS is a browser mechanism that enables controlled access to resources outside a given domain.

CORS defines a way in which a browser and server can interact to determine whether it is safe to allow the cross-origin request.

To prevent cross-site scripting (XSS) and cross-site request forgeries, JavaScript's asynchronous communication such as Ajax follows the same origin policy, which bans access to a different origin. Without CORS configuration, web applications can not access a different origin.

Enabling CORS

To enable CORS, we just need to add Access-Control-Allow-Origin:* to the response header from WEB servers. This header will allow CORS from any source. However, to specify specific domains we can configure CORS like  Access-Control-Allow-Origin:https://codewolfy.com.

Here, We can also specify methods for performing AJAXs or requests.

Enable CORS In Laravel

To enable CORS in Laravel, we can use pre-built external packages or use middleware to create custom functionality. In this example, we will create custom middleware and enable CORS for the application.

Let's create new middleware by Cors name using the below command:

php artisan make:middleware Cors

In this middleware, we will add a CORS header in all requests assigned to this middleware. Let's modify it as per logic:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Set CORS for 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', '*')

    }
}

  After modifying, we need to register middleware into the application. So open Kernel.php and modify as below:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \App\Http\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'cors'          => \App\Http\Middleware\Cors::class, // add this line
];

As of now, our middleware is registered in the application. We can assign this CORS middleware to specific routes or route groups or even all routes.

For example, Here will assign this middleware to the route group.

Route::middleware(['cors'])->group(function () {
    Route::post('/test', 'Controller@test');
    Route::post('/test2', 'Controller@test2');
});

Conclusion

In this post, we have learned about the CORS policy and enabled CORS into the Laravel application with the help of middleware. Here, we have taken a simple example to apply middleware by creating a route group. However, you can apply this middleware to route files or all routes.