Skip to content

Instantly share code, notes, and snippets.

@saaiful
Last active May 6, 2023 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saaiful/3ef381abcdb3d0de7b02f453243bb638 to your computer and use it in GitHub Desktop.
Save saaiful/3ef381abcdb3d0de7b02f453243bb638 to your computer and use it in GitHub Desktop.
Enable CORS via Middleware in Laravel
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class CORS
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$origin = request()->headers->get('origin', '*');
$headers = [
'Access-Control-Allow-Methods' => 'GET, PUT, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization, apitoken, ApiToken',
'Access-Control-Allow-Origin' => $origin,
'Access-Control-Allow-Credentials' => 'true',
];
if ($request->getMethod() == "OPTIONS") {
return response('', 200)->withHeaders($headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
@saaiful
Copy link
Author

saaiful commented Mar 21, 2021

protected $routeMiddleware = []
add 'cors' => \App\Http\Middleware\CORS::class,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment