Laravel request()->all() is empty in booted function when running tests

512 Views Asked by At

I created a trait sets up some Global Scopes based on the query parameters.

It does that by reading from the request() helper and reading the query parameters from the url. Below is the start of the trait:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

trait QueryParamScopes {

    // Todo: add limit and offset functionality.
    // Todo: Add functionality to always return a maximum no. results. add pagination for retrieving.
    // Todo: add wherehas functionality.

    protected static function bootQueryParamScopes() // Todo: write tests
    {
        dd(request()->all()); // this returns []

        $queryParams = static::getQueryParamsByRequest();

        static::handleWhereParams($queryParams['where']);
        static::handleWithParams($queryParams['with']);
        static::handleOrderByParams($queryParams['orderBy']);
        static::handleAppendsParams($queryParams['appends']);
    }

All works as expected but when writing testcases the request()->all() function returns [];

My models use the trait above. In my test I call an endpoint that retrieves the model using

$response = $this->getJson('/v0.1/zipcodes?with[]=dealer');

So I expect request()-all() to return [with => ['dealer']]

Another strange thing is that it is only empty in the trait (maybe because it's all static methods?) when I dd(request()->all()) from the controller method it outputs the query parameters as expected.

Can anyone tell me what is going on here, or how to overcome this.

1

There are 1 best solutions below

3
On

In your function bootQueryParamScopes() it's null because you aren't accepting request. It should be...

function bootQueryParamScopes(Request $request)

Also make sure at the top of the trait you have...

use Illuminate\Http\Request;