Skip to content

Instantly share code, notes, and snippets.

@tomfordweb
Created April 11, 2019 14:30
Show Gist options
  • Save tomfordweb/7ba6e978ce8f5358acbe41e57647ed97 to your computer and use it in GitHub Desktop.
Save tomfordweb/7ba6e978ce8f5358acbe41e57647ed97 to your computer and use it in GitHub Desktop.
Laravel CORS Middlware: Allowing external CORS requests on your Laravel site.
<?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'=> 'GET',
'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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment