Ad

Laravel Request Macro With Static Values

- 1 answer

I was trying to create a lazy-loading pattern in a Request macro that would cache the value for the life of the request.

I put this in my App\Providers\RouteServiceProviderboot() function:

Request::macro('foo', function() {
    static $bar;

    if (is_null($bar)) {
        $bar = 'was not null';
        return 'was null';
    }

    return $bar;
});

Every time I call request()->foo() or Request::foo() it returns 'was null'.

My question is two-fold:

  1. How should I accomplish this pattern?
  2. Why doesn't it work as written?
Ad

Answer

I found that I can accomplish the pattern this way:

Request::macro('foo', function() {
    if (! isset(request()->bar)) {
        request()->bar = 'was not null';
        return 'was null';
    }

    return request()->bar;
});

I haven't found my answer to #2, though.

Ad
source: stackoverflow.com
Ad