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.

Top comments (0)