How to retrieve items from the cache in view in Laravel?

6.2k Views Asked by At

I've stored some data in Laravel 5.5 cache in Service Provider as you can see in following:

class DataServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $user = Cache::rememberForever('user', function () {
            return array('name' => 'jack', 'age' => 25);
        });
    }

    public function register()
    {
        //
    }
}

I retrieve items from the cache in controller by this:

  $user= Cache::get('user');

But I need to retrieve cache items within views (blade), How can I access them directly in views (blade) (without passing cache as variable)? I just want to store data in cache once, and access to it everywhere in my app with no more steps, is it possible?

3

There are 3 best solutions below

0
DevK On BEST ANSWER

Use the cache helper:

{{ cache('user')['name'] }}
0
Hasan Teymoori On

Cache Facade: {{ Cache::get('user')['name'] }}
cache helper: {{ cache()->get('user')['name'] }} or {{ cache('user')['name'] }}

0
Purvesh On

I would do it like this

@php 
    $user = Cache::get(“user”);
@endphp

 {{ $user[“name”]; }}