Updating Laravel TrustProxies Middleware after Framework Version Upgrade

Posted by

When upgrading Laravel from version 5.7 to version 10, it’s essential to address changes in middleware configurations to ensure the smooth operation of your application. The issue related to the TrustProxies middleware and provide a solution to update the code for Laravel 10 compatibility.

After upgrading to Laravel 10, the existing TrustProxies middleware may become incompatible due to changes in the framework. The middleware is responsible for configuring trusted proxies and headers, and Laravel 10 introduces adjustments to how this is handled.

The OldTrustProxies.php:

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies;

    /**
     * The current proxy header mappings.
     *
     * @var array
     */
    protected $headers = [
        Request::HEADER_FORWARDED => 'FORWARDED',
        Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
        Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
        Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
        Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
    ];
}

The Solution: To resolve this issue and make the TrustProxies middleware compatible with Laravel 10, you should make the following changes:

The Updated TrustProxies.php:

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Http\Middleware\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array|string|null
     */
    protected $proxies = '*';

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_FOR |
        Request::HEADER_X_FORWARDED_HOST |
        Request::HEADER_X_FORWARDED_PORT |
        Request::HEADER_X_FORWARDED_PROTO |
        Request::HEADER_X_FORWARDED_AWS_ELB;
}

Additionally, ensure that you have the latest version of the fideloper/proxy package installed by running:

composer require fideloper/proxy

Updating middleware configurations is a crucial step when upgrading Laravel versions. By making the necessary adjustments to the TrustProxies middleware, you ensure that your application remains compatible with Laravel 10, allowing for a seamless transition and continued stability.

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] Updating Laravel TrustProxies Middleware after Framework Version Upgrade […]

trackback

[…] Updating Laravel TrustProxies Middleware after Framework Version Upgrade […]

2
0
Would love your thoughts, please comment.x
()
x