Ajax – Cross-Origin Request Blocked in Larave?

Ajax – Cross-Origin Request Blocked in Larave?

In this post we will give you information about Ajax – Cross-Origin Request Blocked in Larave?. Hear we will give you detail about Ajax – Cross-Origin Request Blocked in Larave?And how to use it also give you demo for it if it is necessary.

When i was working on my laravel 5 project and i was making backend API, i created successfully but when front-end developer call API which i made. It’s return like: “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at . (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).” and i did try to how to solve this issue. I did also try with jquery and angularjs from backend but result nothing always.

At last i did found how to solve this issue, i made one middleware that allows to Cross-Origin Request in your laravel application. so let’s create new middleware :

Create Middleware

php artisan make:middleware CORS

On now you can check on Middleware(app/Http/Middleware) directory, you can find CORS.php file and put bellow code on that file.


namespace AppHttpMiddleware;

use Closure;

class CORS


    public function handle($request, Closure $next)


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

        $headers = [

            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',

            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'


        if($request->getMethod() == "OPTIONS") {

            return Response::make('OK', 200, $headers);


        $response = $next($request);

        foreach($headers as $key => $value)

            $response->header($key, $value);

        return $response;



Ok, now register new created middleware on Kernel.php(app/Http/Kernel.php) file and append following line.


namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel




    protected $routeMiddleware = [


        'cors' => AppHttpMiddlewareCORS::class,



Now we are ready to use ‘cors’ middleware on route file so, use following way:


Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {

    Route::post('register', 'APIController@register');

    Route::post('login', 'APIController@login');


Hope this code and post will helped you for implement Ajax – Cross-Origin Request Blocked in Larave?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  70  =  76

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US