Ajax – Cross-Origin Request Blocked in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you how to Ajax Cross origin Request blocked in laravel. When i was at working on my laravel project and when i was try to making backend API, that time i was created that successfully but when my front-end developer call that API which i was made. It’s was return as like: “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://tpwork/register. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).” and on that time i did try to learn how to solve this issue. And I was also try with this by using jquery from backend but the result was nothing always.

At last i can found a solution how to solve this issue, i made one middleware for that allows to Cross-Origin Request in our laravel application.

so let’s need to create new middleware :

Create Middleware

php artisan make:middleware CORS

Okay now we can check on this Middleware(app/Http/Middleware) directory, we can also find CORS.php file and need to put bellow code on that file.

app/Http/Middleware/CORS.php

namespace App\Http\Middleware;
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 need register new created middleware on Kernel.php(app/Http/Kernel.php) file and need to append following line.

app/Http/Kernel.php

namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
	...
	...
    protected $routeMiddleware = [
        ...
        'cors' => \App\Http\Middleware\CORS::class,
    ];
}

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

Read Also : How to get current month data in MySql PHP ?

app/Http/routes.php

Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {
    Route::post('register', '[email protected]');
    Route::post('login', '[email protected]');
});

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →