Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

thebigk's avatar
Level 13

Eloquent User Provider Causing Duplicate Query

I'm required to calculate the current 'rating' of a user (model) based on a relationship with Activity(model). I therefore have the following in my User model:

protected $with = ['lastActivity'];
protected $appends = ['rating'];

public function lastActivity() {
  return $this->hasOne(Activity::class, 'user_id')->latest();
}

public function getRatingAttribute() {
    $user_points = $this->lastActivity->total;
        return ($user_points >= 1000) ? "Level 1" : "Level 2";

}

Because this needs to be used site-wide, I've used $appends. The only problem is that this is causing duplicate query on my blog show pages. The first one is for rendering the user in the site's top navigation

/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php:52 :

Query: 
select * from `activity_points` where `activity_points`.`user_id` in (1) order by `created_at` desc

and the second query is being run when I'm loading blog post along with replies: -

My statement -
$post   =   Post::where('id', $post)->with(['author',  'replies.author', 'replies.likes.giver'])->withCount('likes')->first();


app/Http/Controllers/Blogs/PostsController.php:44
Query:
select * from `activity_points` where `activity_points`.`user_id` in (1) order by `created_at` desc

What could be a possible fix for this?

0 likes
4 replies
jlrdw's avatar

Instead of

$user_points >= 1000) ? "Level 1" : "Level 2"

Couldn't you have a field to store the level. Kind of like a role field except it's level. Then you won't need appends. Just show the level when and where needed.

And sorry if I'm not understanding something here.

thebigk's avatar
Level 13

@jlrdw - Yeah; saving the level in the database would be the ultimate option. What I presented with is a much simplified version of the problem.

I'm just wondering if there's a way to avoid the duplicate query being run when EloquentUserProvider and my own statement operates. I can deal with duplicate queries to some extent; but still wondering if there's anything wrong on my part.

jlrdw's avatar

Exactly what is returned here, and how many results.

select * from `activity_points` where `activity_points`.`user_id` in (1) order by `created_at` desc

Seems that you could use session to store and display if you don't want to have an extra field.

But the way it's coded, one for nav and one for loading data, it's of course going to run twice.

Can you place image here of nav bar. To show image:

![Alt image](image url)

And don't put in a code block.

Snapey's avatar

its your with statement rather than the append that causes the extra query every time you load any user

Please or to participate in this conversation.