create a new middleware: app/Http/Middleware/cors.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
add the cors middleware to app/Http/Kernel.php
protected $routeMiddleware = [
//default laravel middleware
'cors' => \App\Http\Middleware\Cors::class,
];
add the new cors middleware to your route
Route::get('/broadcast', function () {
broadcast(new hello());
});
})-> middleware('cors');
---caution---
this will now accept requests from ANYWHERE.
this is fine on localhost but when you move to a live server you need to change:
->header('Access-Control-Allow-Origin', '*')
to
->header('Access-Control-Allow-Origin', 'http://www.yourdomain.com')
or you need to create an api key to pass along with each request so you can have the public api (not reccomended but is a viable workaround)