Good practices for variables in Laravel's layout files

30 views Asked by At

I don't know how to do it in more elegant way.

I have the menu in a layout file with tags with the classes "menu__item" and I want to add the class "menu__item--active" to the current link.

I did it that way: web.php

    Route::get('/page/foo', [TestController::class, 'foo'])->name('foo');
    Route::get('/page/bar', [TestController::class, 'bar'])->name('bar');
    Route::get('/page/baz/{param}', [TestController::class, 'baz'])->name('baz');

layout.blade.php

    <!-- somewhere in the beginning -->
    @php($template = Route::current()->getName())
    <!--and later -->
    <a class="menu__item @if ($template === 'foo') menu__item--active @endif" href="/page/foo">Foo</a>
    <a class="menu__item @if ($template === 'bar') menu__item--active @endif" href="/page/baz">Bar</a>
    <a class="menu__item @if ($template === 'baz') menu__item--active @endif" href="/page/baz/1">Baz</a>

But it seems that @php thing is not an elegant way. What is good practices to do it?

0

There are 0 answers