Laravel TutorialChange default routing behaviour in Laravel 5.2.31 +CustomException class in LaravelDeploy Laravel 5 App on Shared Hosting on Linux ServerLaravel ArtisanLaravel AuthenticationLaravel AuthorizationLaravel Blade TemplatesLaravel CashierLaravel CollectionsLaravel Common Issues & Quick FixesLaravel ConstantsLaravel ControllersLaravel Cron basicsLaravel Cross Domain RequestLaravel Custom Helper functionLaravel DatabaseLaravel Database MigrationsLaravel Database SeedingLaravel Directory StructureLaravel DockerLaravel EloquentLaravel Eloquent : RelationshipLaravel Eloquent: Accessors & MutatorsLaravel Eloquent: ModelLaravel Error HandlingLaravel Events and ListenersLaravel Filesystem / Cloud StorageLaravel Form Request(s)Laravel Getting started with laravel-5.3Laravel HelpersLaravel HTML and Form BuilderLaravel InstallationLaravel Installation GuideLaravel Introduction to laravel-5.2Laravel Introduction to laravel-5.3Laravel lumen frameworkLaravel Macros in Eloquent RelationshipLaravel MailLaravel MiddlewareLaravel ObserverLaravel PackagesLaravel PaginationLaravel Permissions for storageLaravel PoliciesLaravel QueuesLaravel RequestsLaravel Route Model BindingLaravel RoutingLaravel SeedingLaravel ServicesLaravel SocialiteLaravel Task SchedulingLaravel TestingLaravel Token Mismatch Error in AJAXLaravel use fields aliases in EloquentLaravel Useful linksLaravel ValetLaravel ValidationMultiple DB Connections in LaravelNaming Files when uploading with Laravel on WindowsRemove public from URL in laravelSparkpost integration with Laravel 5.4

Laravel Cross Domain Request

From WikiOD

Introduction[edit | edit source]

Sometimes we need cross domain request for our API's in laravel. We need to add appropriate headers to complete the cross domain request successfully. So we need to make sure that whatever headers we are adding should be accurate otherwise our API's become vulnerable. In order to add headers we need to add middleware in laravel which will add the appropriate headers and forward the requests.

CorsHeaders[edit | edit source]


namespace laravel\Http\Middleware;

class CorsHeaders
   * This must be executed _before_ the controller action since _after_ middleware isn't executed when exceptions are thrown and caught by global handlers.
   * @param $request
   * @param \Closure $next
   * @param string [$checkWhitelist] true or false Is a string b/c of the way the arguments are supplied.
   * @return mixed
  public function handle($request, \Closure $next, $checkWhitelist = 'true')
    if ($checkWhitelist == 'true') {
      // Make sure the request origin domain matches one of ours before sending CORS response headers.
      $origin = $request->header('Origin');
      $matches = [];
      preg_match('/^(https?:\/\/)?([a-zA-Z\d]+\.)*(?<domain>[a-zA-Z\d-\.]+\.[a-z]{2,10})$/', $origin, $matches);

      if (isset($matches['domain']) && in_array($matches['domain'], ['']) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Expose-Headers: Location');
        header('Access-Control-Allow-Credentials: true');

        // If a preflight request comes then add appropriate headers
        if ($request->method() === 'OPTIONS') {
          header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH');
          header('Access-Control-Allow-Headers: ' . $request->header('Access-Control-Request-Headers'));
            // 20 days
          header('Access-Control-Max-Age: 1728000'); 
    } else {
      header('Access-Control-Allow-Origin: *');

    return $next($request);