DEV Community

Cover image for Save server resource in Laravel
Shahrukh A. Khan
Shahrukh A. Khan

Posted on

Save server resource in Laravel

How do you save server resource in Laravel 11?

Go to routes/web.php

and add middleware to your route or route group just remember the key which will be using throughout the application in this case I am using weather as key to limit the request by User or IP. just remember whatever key you use should be same as the key in app/Providers/AppServiceProvider.php

so my route/web.php should look like this when I use the middleware with the single route

Route::get('/your-url', function () {
    return response()
        ->json([
            'data' => 'data will be here'
        ]);
})->middleware(['throttle:weather']);
Enter fullscreen mode Exit fullscreen mode

or if you want to use route group

Route::middleware(['throttle:weather'])->group(function () {
    // User CRUD controller
    Route::resource('/users', UserController::class);

    // Change Password View
    Route::get('/profile/change-password', [UserController::class, 'changePassword'])->name('change.password');

    // Change Password Store
    Route::post('/profile/change-password', [UserController::class, 'changePasswordStore'])->name('change.password.store');
});
Enter fullscreen mode Exit fullscreen mode

Than inside your app/Providers/AppServiceProvider.php within boot method you can limit the user or ip make sure to import the following namespaces

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        RateLimiter::for('weather', function (Request $request) {
            return Limit::perMinute(10)
            ->by($request->user()?->id ?: $request->ip()); // 10 request per minute per user or ip

        });
    }
}
Enter fullscreen mode Exit fullscreen mode

of if you want to limit normal user vs logged in user use the following.

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        RateLimiter::for('weather', function (Request $request) {
            // Rate Limit by Logged in User vs Normal User
            return $request->user() ?
                Limit::perMinute(2)->by($request->ip()) :
                Limit::perMinute(1)->by($request->ip());
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

By following this you can now save your server resource and keep user informed they are only allowed certain request per minute this could for per seconds and hours following are some useful methods.

// perSecond takes 1 argument
Limit::perSecond($maxAttempts: 1)->by($key: $request->ip())

// perMinute takes 1 argument
Limit::perMinute($maxAttempts: 1)->by($key: $request->ip())

// perMinutes takes 2 argument
Limit::perMinutes($decayMinutes: 1, $maxAttempts: 10)->by($key: $request->ip())

// perHour takes 2 argument
Limit::perHour($maxAttempts: 100, $decayHours: 1)->by($key: $request->ip())
Enter fullscreen mode Exit fullscreen mode

when you want to use limit you can save server resource when you have hosted your application where your server provider charges for the resource.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay