skip to Main Content

For Laravel post request’s parameter get with $request->all();

This function itself does trimming for the request parameter if there is any preceding space.
I try to use $_POST instead of $this->request->all(); it is not trimming any request parameter and works as expected.

$_POST is not safe to use.

please share suggestions/ideas how can I do that without trimming any value ?

2

Answers


  1. You have HTTP middlewares, one of those trims the data. Check this: https://github.com/laravel/laravel/blob/9ae75b58a1ffc00ad36bf1e877fe2bf9ec601b82/app/Http/Kernel.php#L22

    /**
     * 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 = [
        // AppHttpMiddlewareTrustHosts::class,
        AppHttpMiddlewareTrustProxies::class,
        IlluminateHttpMiddlewareHandleCors::class,
        AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    ];
    

    You can see there is a AppHttpMiddlewareTrimStrings::class, you have to remove that one.

    Login or Signup to reply.
  2. The trimming of your input value happens to be due to an active global middleware. The AppHttpMiddlewareTrimStrings middleware to be exact.

    Since you say you do not want to disable the middleware for your entire application, you should look into disabling it only for a specific route or routes. You can do so in two ways:

    1. Single route:
    Route::post('my-route', 'MyRouteController@myRoute')->withoutMiddleware(['trimStrings']);
    
    1. Group of routes:
    Route::withoutMiddleware([AppHttpMiddlewareTrimStrings::class])->group(function () {
        Route::post('my-route', 'MyRouteController@myRoute');
    
        // Add additional routes within this group.
    });
    

    However, please note that the withoutMiddleware method can only remove route middleware and does not apply to global middleware. Since the TrimStrings is by default a global middlewere, you will still need to remove it from the $middleware array in the app/Http/Kernel.php file and add the TrimStrings middleware manually again for all routes where you do not want to remove it. To do so, use a similar looking route group syntax as demonstrated in option 2, like so:

    Route::middleware([AppHttpMiddlewareTrimStrings::class])->group(function () {
        // Place all the routes you already had here.
    });
    

    You can also take a look at the documentation: https://laravel.com/docs/10.x/middleware#excluding-middleware

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search