#Most optimized method of including repeat code in a blade template?

1 messages · Page 1 of 1 (latest)

west steeple
#

I need to include the following code for 10 columns, over 300 rows (So 3000 times) with different values each time

@if ($column->assigned_at == null && $column->completed_at == null)
    --
@elseif ($column->assigned_at != null && $column->completed_at == null)
    {{\Carbon\Carbon::parse($column->assigned_at)->format('m/d')}}
@else
    {{\Carbon\Carbon::parse($column->completed_at)->format('m/d')}}
@endif
@if ($column->assigned_to != null)
    {{$people[$column->assigned_to]->initials}}
@endif

What would be the most optimized way to include this in a blade template loop? I tried using a component (Like you see above) for just ONE Of the columns and it added 60+ ms to the load time and I'm now loading over 300 extra templates

#

I'm calling it with

<x-table.datename_section :people="$people" :column="$data->coltwo" />
woeful heron
#

@west steeple If these are coming back from a model, then add casts for your assigned_at and completed_at column so they’re parsed as Carbon objects once, rather than 3,000 times in a single page load.

#
protected $casts = [
    'assigned_at' => 'datetime',
    'completed_at' => 'datetime',
];
west steeple
#

That'll help a bit, ty - but what about the fact I'm loading 3k views?

#

casting shaved 200ms off

woeful heron
#

You could move that logic to a method instead.

#

There’s not a lot of actual rendering going on there; just conditions that end up returning a different value.

west steeple
#

I'm just wondering if there's some sort of way to just ... Not load 3k views 😅. Wht do you mean move the logic into a method?

#

I want to reuse the simple logic/view in case I need to update it in the future I won't have to update it a bunch of times

woeful heron
#

But your include isn’t returning any HTML or anything. It’s just returning some string value dependent on conditions.

#

So have a method on your model instead that returns that string.

west steeple
#

Ah! Okay I see

woeful heron
#

That way you’re not loading and compiling hundreds of views.