-1

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.

Gijs Beijer
  • 560
  • 5
  • 19
  • What do you expect `request()->all()` would return in your test cases? From where would it return that? – N69S Apr 28 '22 at 12:52
  • Hi @N69S, I've edited the question to include the answers to your questions. Thanks for the feedback. – Gijs Beijer Apr 28 '22 at 13:05
  • and where would `[with => ['dealer']]` come from, are you not starting your tests from CLI command? – N69S Apr 28 '22 at 13:23
  • It comes from the uri $response = $this->getJson('/v0.1/zipcodes?with[]=dealer'); calls the URL – Gijs Beijer Apr 28 '22 at 13:24

1 Answers1

0

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;
  • As an afterthought you could just pass what you need from the controller too. Since you probably are using request on the controller action. Just pass the variable you need sorted to your trait. And now that I'm looking you aren't really doing anything in your trait. Your trait should return a value back to your controller action. –  Apr 29 '22 at 16:33
  • I do not have to pass anything when using the request helper function, right? Shouldn't that resolve the Request object from the service container – Gijs Beijer May 01 '22 at 05:26
  • Also the code works, only not when testing – Gijs Beijer May 01 '22 at 05:27