0

Right now I've got this in my Settings.php model:

public function scopeFromCache($query)
{
    \Cache::rememberForever('settings', function () use ($query) {
        return $query->first();
    })->first();
}

Then in the boot method from my AppServiceProvider I do this:

$settings = Settings::fromCache()->first();

Is it possible to get the settings without the ->first() like this:

$settings = Settings::fromCache();

So instead of returning a query builder return the object?

1
  • But isn't that what the first() method is doing, returning the first object from the Collection instead of the query builder? Why don't you wanna do this? Commented Jun 16, 2017 at 19:48

1 Answer 1

1

To answer your question, no.


I would take another approach, since you are caching something forever (settings), I would make custom helper to get you these settings.

So create file app/helpers.php, in composer.json add

"files": [
    "app/helpers.php"
]

in "autoload" array.

Now forget about using scope, and create method (function) to use cache, just like you are doing now:

if ( ! function_exists('settings')) {
    function settings()
    {
        return Cache::rememberForever('settings', function () {
            return Settings::first();
        });
    }
}

Now anywhere in your project just call settings() and you get your object.

Sign up to request clarification or add additional context in comments.

3 Comments

Much better thanks. Can I use settings() in my views aswel or do I have to add it in View::composer?
You don't have to add it to composers, use it anywhere you like it is now global function, you can fire up tinker ($ php artisan tinker) and use it there as well.
Thanks really helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.