Skip to content

Instantly share code, notes, and snippets.

@technoknol
Created April 26, 2017 14:10
Show Gist options
  • Select an option

  • Save technoknol/1a35ca4b150215f491d5c807940bd4ef to your computer and use it in GitHub Desktop.

Select an option

Save technoknol/1a35ca4b150215f491d5c807940bd4ef to your computer and use it in GitHub Desktop.
Enable CORS in laravel 5.4
<?php
# File: app\Http\Middleware\CORS.php
# Create file with below code in above location. And at the end of the file there are other instructions also.
# Please check.
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: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
];
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;
}
}
# File:: app\Http\Kernel.php
# Add following line in `protected $middleware` Array.
# \App\Http\Middleware\CORS::class
# And following in `protected $routeMiddleware` Array
# 'cors' => \App\Http\Middleware\CORS::class
@mofrubel
Copy link
Copy Markdown

mofrubel commented Jun 17, 2017

use

$response = $next($request);
foreach ($headers as $key => $value)
     $response->headers->set($key, $value); 
return $response;

instead of

$response = $next($request);
foreach ($headers as $key => $value)
     $response->header($key, $value);
return $response;

because it throws an exception of not getting header method symphony component! like
"Call to undefined method Symfony\Component\HttpFoundation\Response::header()"

@iateadonut
Copy link
Copy Markdown

Great way to do it! I'm really glad you posted this file. And it makes it really easy to eliminate methods you don't want CORS on.

@CamiloEspinoza
Copy link
Copy Markdown

The best CORS solution I found for Laravel!

@MashRoofa
Copy link
Copy Markdown

REALLLY THANK YOU!

@rullymartanto
Copy link
Copy Markdown

Wow,.. and magic happen ,..... Thanks

@cache-crusader
Copy link
Copy Markdown

cache-crusader commented Oct 26, 2017

You've saved my life !!! thanks mate !!

@kwebble
Copy link
Copy Markdown

kwebble commented Nov 6, 2017

Beware: this allows clients from any domain, the *-value, to access the application. This may be acceptable for public API's. For other applications you would normally restrict access and only grant access to domains you control or allow access.

@Ipzzer
Copy link
Copy Markdown

Ipzzer commented Nov 30, 2017

Very good and small solution. Thanks!

@Aaituov
Copy link
Copy Markdown

Aaituov commented Dec 10, 2017

I embeded this code. But there's what I got as an error message. What should I do? Thank you!! :

1/1) ReflectionExceptionClass App\Http\Middleware\CORS does not exist

in Container.php (line 729)
at ReflectionClass->__construct('App\Http\Middleware\CORS')in Container.php (line 729)
at Container->build('App\Http\Middleware\CORS')in Container.php (line 608)
at Container->resolve('App\Http\Middleware\CORS')in Container.php (line 575)
at Container->make('App\Http\Middleware\CORS')in Application.php (line 728)
at Application->make('App\Http\Middleware\CORS')in Pipeline.php (line 138)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in TransformsRequest.php (line 30)
at TransformsRequest->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in ValidatePostSize.php (line 27)
at ValidatePostSize->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in CheckForMaintenanceMode.php (line 46)
at CheckForMaintenanceMode->handle(object(Request), object(Closure))in Pipeline.php (line 148)
at Pipeline->Illuminate\Pipeline{closure}(object(Request))in Pipeline.php (line 53)
at Pipeline->Illuminate\Routing{closure}(object(Request))in Pipeline.php (line 102)
at Pipeline->then(object(Closure))in Kernel.php (line 151)
at Kernel->sendRequestThroughRouter(object(Request))in Kernel.php (line 116)
at Kernel->handle(object(Request))in index.php (line 53)

@jigarzon
Copy link
Copy Markdown

@Aaituov you have to dump autoload:
composer dump-autoload

@aborzanovic
Copy link
Copy Markdown

Why is the "Access-Control-Allow-Origin" header added via header() function and not as the others?

@shailesh87
Copy link
Copy Markdown

Easy and good solution; Thanks

@leandrocubas
Copy link
Copy Markdown

The best solution that i found until now.. it works perfectly.. Thanks a Lot Dude..

@kingsloi
Copy link
Copy Markdown

By far best solution, was running into random/sporadic issues with Barry's laravel-cors, found this and worked perfectly every time.

👍

@joejose99
Copy link
Copy Markdown

joejose99 commented Feb 25, 2018

had the same error. i run auto load but still can't work it out

ReflectionExceptionClass App\Http\Middleware\CORS does not exist

@sagerio
Copy link
Copy Markdown

sagerio commented Feb 26, 2018

Thanks mate!
Wasted hours to find a solution for this...

@joejose99
Copy link
Copy Markdown

thanks get it working namespace was the issue

@joejose99
Copy link
Copy Markdown

hey guys does anyone knows how to tackle the issue of CSRF-TOKE I'll been trying to fixed this for days now but can't get through. I don't know what could be wrong, im having this error. 500 (Internal Server Error) . im runing laravel 5.4 here's is the bit of ajax code.

var requestData= JSON.stringify(dataArray);

$.ajaxSetup({
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},

	}); 
	  $.ajax({
		  data:{"data":requestData, "method":'POST',"_token":'{{csrf_token()}}'},
	 type:"POST",
	url: "result",
	dataType:"JSON",
	 success: function(data) {
         $("#tb1").html(data);
		 
     } 
	   
 });  

@besrabasant
Copy link
Copy Markdown

besrabasant commented Mar 14, 2018

Awesome.

But I had to remove

header("Access-Control-Allow-Origin: *");

and add it to

$headers = [
        "Access-Control-Allow-Origin"   => "*",
        // Other Options
];

instead to make it work with my tests.

@AnApluss
Copy link
Copy Markdown

Awesome... Thanks mofrubel, this works for me too

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