You have a property on a model where you can automatically load relationships. It's called with and looks like this in your case
class User extends Authenticatable
{
/**
* The relations to eager load on every query.
*
* @var array
*/
protected $with = ['subscription.plan.features'];
}
Now the user should always have these properties available if they have any!
Another solution is using caching inside your hasFeature method or any other method where you fetch it.
public function hasFeature($feature_id)
{
Cache::remember('feature-' . $feature_id . '-' . auth()->id(), $minutes, function () use ($feature_id) {
return $this->features()
->where('slug', '=', $feature_id)
->isNotEmpty();
});
}
The first option looks nice, but then if you update something in one of the models your user has you might need to reload the relations of the user otherwise you get weird results.
Let me know if any of this works for you!