Laravel Gzip is a simple and effective way to gzip your response for a better performance.
You can install the package via composer:
composer require erlandmuchasaj/laravel-gzipBrotli provides 15-20% better compression than Gzip and is supported by all modern browsers. To install the Brotli extension, you can use PECL:
pecl install brotlisudo apt-get install php-brotli
# or
sudo pecl install brotliNote
If Brotli is not available, the package will automatically fall back to Gzip compression.
Publish the configuration file using artisan.
php artisan vendor:publish --provider="ErlandMuchasaj\LaravelGzip\GzipServiceProvider"This package has a very easy and straight-forward usage.
Just add the middleware in bootstrap/app.php, like so:
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
// ...
)
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\ErlandMuchasaj\LaravelGzip\Middleware\GzipEncodeResponse::class);
})
// ...Just add the middleware to the $middleware array in app/Http/Kernel.php like so:
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
\ErlandMuchasaj\LaravelGzip\Middleware\GzipEncodeResponse::class,
//...
];Important
In a previous version, we recommended adding the middleware to the web middleware group. Now, we recommend adding
to global $middleware because we want to apply gzip to all requests. Additionally, registering the middleware in the
web group caused debugger to break.
Also, if you are using spatie/laravel-cookie-consent package, you should register this middleware before the
\Spatie\CookieConsent\CookieConsentMiddleware::class middleware.
[!PS] To see the package working, the application env should be
APP_ENV=productionand theAPP_DEBUG=false
That's it! Now your responses will be gzipped.
I tested this package with a fresh installed laravel in homepage and got:
No Gzip => 72.9kb
With Gzip => 19.2kb *
I invest a lot of time and resources into creating best in class open source packages.
If you found this package helpful you can show support by clicking on the following button below and donating some amount to help me work on these projects frequently.
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please see SECURITY for details.
The MIT License (MIT). Please see License File for more information.