S
S
sp-megamen2018-04-20 12:48:35
Laravel
sp-megamen, 2018-04-20 12:48:35

How to cache model with attributes in laravel?

Hey!
I have a user model with an email accessor that just needs to pull data from a remote server.
More or less like this:

public function getEmailAttribute(){
    $curl = new Curl;
    $responseJson = $curl->post('https://mydb.remote/api/user.json',array(
        'user_id'=>$this->id
    ));
    $response = json_decode($responseJson);
    return $response->email;
}

But when I try to work with the cache, the getEmailAttribute function is called every time, even though the user himself is cached
$value = Cache::remember('users', $minutes, function () {
    return User::find($id);
});

Can you please tell me how to cache the model along with the attributes? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yan-s, 2018-04-20
@Yan-s

you just need to pull data from a remote server

Doesn't sound very good...
Accessor should be executed every time it is accessed. So you need to create an attribute to store the email, which will be filled before caching. Or separately cache the result of the getEmailAttribute() execution inside this function itself.
And if it comes to that, the interaction with another service needs to be moved to a separate place, the email should be cached there, then getEmailAttribute() will get the cached address.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question