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

Romas D.'s avatar

Laravel Nova n+1 problem when running sql inside fields()

For some reason, I need dynamically add columns in the fields method. This is not only dynamic columns but also contains computed fields.

This is very simplified version of what I'm trying to do inside fields():

$additional_fields = [];

Product::visible()->each(function($attr) use (&$additional_fields, $request) {
    $additional_fields[] = Text::make($attr->name, function() use ($attr, $request) {
        $first_subscription = $this->subscriptions()->whereHas('product', function($q) {
            return $q->where('visible', 1);
        });

        ...
    }
}

This, of course, causing the N+1 problem as statements for Product and Subscription are executed on every row.

I need to move this piece of code somewhere else and run it only once. I can't figure out how to do this yet.

0 likes
1 reply
bugsysha's avatar

Have you tried adding with()?

$first_subscription = $this->subscriptions()->with('product')->whereHas('product', function($q) {
  return $q->where('visible', 1);
});

Please or to participate in this conversation.