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

MoFish's avatar

View :: Assigning a variable without using @php?

Hi,

I have an administration panel with a template editor.

I would like to improve on this slightly to give the admin the ability to retrieve particular data, and render it using blade in whatever format they wish. For example a set of hyperlinks.

The ultimate goal is to have some code to allow me to assign data to a variable, without using @php tags, but my limited understanding is that what i'm looking for may simply not be possible.

I have used liquid in the past which has a very similar approach to what I would like and i'm trying to find the best way to achieve something like the way they assign variables: https://docs.microsoft.com/en-us/powerapps/maker/portals/liquid/liquid-objects#weblinks

Liquid example

{% assign nav = weblinks[Navigation] %}
{% if nav %}
<ul>
  {% for link in nav.weblinks %}
    <li>{{ link.name | escape }}</a></li>
  {% endfor %}
</ul>
{% endif %}

In order for me to replicate this, I have tried a number of things:

A. Created a function which works well, but the top line in the @php tags look a little messy. If there is anything i could do to make this top line 'less messy' then this would be the solution i'm after.

@php $nav= collection("Navigation"); @endphp

@if($nav)
    @foreach ($nav->items as $m)
        {{ $m->name }}
    @endforeach
@endif

B. I then tried to create a blade directive as that syntax looked a little better @collection("Navigation") but could not seem to assign this to a variable in my views.

// nav ???? = @collection("Navigation");

@if($nav)
    @foreach ($nav->items as $m)
        {{ $m->name }}
    @endforeach
@endif

C: I then tried using a component, but again could not assign the data to a variable for use in my template. I understand that components have their very own templates and my 'rendering' part to go inside, but i would like to be able to render a navigation by name in any template and control how this displays.

<x-navigation name="Navigaton" />

Is there any clever method for this? or is what i'm looking for just not possible?

Is method A the best and cleanest way? that's the best of the bunch i have so far.

Thanks,

0 likes
3 replies
Snapey's avatar

it's really hard to try and understand what you are trying to do

what's this collection method doing

$nav= collection("Navigation");
MichalOravec's avatar
Level 75

You can assing it in if statement directly

@if ($nav = collection('Navigation'))
    @foreach ($nav->items as $m)
        {{ $m->name }}
    @endforeach
@endif
MoFish's avatar

@michaloravec That is exactly what i was after! I didn't know you could do an assignment in the if.

Perfect, Thanks!

Please or to participate in this conversation.