如何缓存当前经过身份验证的用户? (Laravel 5)

Description

In my situation, I don't have a users table locally, but I have an api that will provide me a list of users.


getUsers()

I modify my getUsers() for my Auth::user() in app/Auth/ApiUserProvider.php

protected function getUsers()
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    curl_close($ch);

    return $response['data'];
}

Issue

Each time, I used Auth::user() in my code. It makes a call to my API .../vse/accounts It effects a lot of latency in my application.


Try#1

Session

protected function getUsers()
{

    if(Session::has('user')){
        return Session::get('user');
    }else{
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);
        $user = $response['data'];
        Session::put('user',$user);
        return $user;
    }

}

Result

It takes 2 seconds longer. :(


Try#2

Cache

protected function getUsers()
{
    $minutes = 60;
    $value = Cache::remember('user', $minutes, function() {
        //your api stuff
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);
        $user = $response['data'];
        return $user;
    });
}

How do I solve this ?

Should I start using cache ? If so, how do I modify what I have to do something like that ?

Should I store it in the session ?

I'm open to any suggestions right now.

Any hints / suggestions on this will be much appreciated !

You can do this

protected function getUsers() {
    $minutes = 60;
    $user = Cache::remember('user', $minutes, function () {
        //your api stuff
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');
        $response = curl_exec($ch);
        $response = json_decode($response, true);
        curl_close($ch);
        return $response['data'];
    });
         return $user;
}

this should work

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist -laravel docs

you will get the user from the cache or, if he don't exist, retrieve user from the api and add him to the cache