Best approach for retrieving data from within a loop of posts with Blade?

The ACF variables in blade template thread that @nathobson posted has lots of techniques. Good read.

You are on the right track. Plus there are probably a half-dozen ways to skin this cat, depends on your style. And sometimes there is just no way around throwing in a few @php directives here and there.

My preferences on using @php is to sometimes not use them.

// Instead of this
//  <a href="@php echo get_the_permalink($post->ID) @endphp" class="button">Visit page</a>
<a href="<?= get_the_permalink($post->ID) ?>" class="button">Visit page</a>

Use the self-enclosed version of @php (note the absence of a semi-colon at end of statement)

// Instead of this
// @php $posts = $fields['quick_links']; @endphp
@php( $posts=$fields['quick_links'] )

And sometimes combine a set and if together

// Instead of this
// @php $posts = $fields['quick_links']; @endphp
//    @if($posts)
@if( @php( $posts=$fields['quick_links'] ) )
1 Like