When I pass my custom helper function as a variable to Laravel Blade, the bug occurs when I click a link to a new page. The error will read the variable was not found. There are a total of 6 navigation links, the first variable pass to the nav link is read by Laravel blade, the other are not. I’ll provide example code below.
Utilities/Helper class example – my custom helper function
<?php
namespace AppUtilities;
class Helper
{
public static function activePage(string $pageUrl): string
{
$requestUri = $_SERVER['REQUEST_RUI'];
return $requestUri === $pageUrl ? "color=var(--sky)" : "color=var(--mud)";
}
}
Controller/Home Action example
<?php
namespace AppHttpControllers;
use AppHttpControllersBaseController;
use AppUtilitiesHelper;
use IlluminateViewView;
class Home extends BaseController
{
public function __construct(
private Helper $helper,
){}
public function index(): View
{
reutrn view('home', [
'helper' => $this->helper::class,
]);
}
}
Laravel Blade Template home page example
<li class="nav-links">
<a href="{{ url('/') }}" style="{{ $helper::activePage('/') }}">Home</a>
<a href="{{ url('/services') }}" style="{{ $helper::activePage('/services') }}">Services</a>
<a href="{{ url('/clients') }}" style="{{ $helper::activePage('/clients') }}">Clients</a>
<a href="{{ url('/about') }}" style="{{ $helper::activePage('/about') }}">About</a>
<a href="{{ url('/blog') }}" style="{{ $helper::activePage('/blog') }}">Blog</a>
<a href="{{ url('/contact') }}" style="{{ $helper::activePage('/contact') }}" class="contact-link">Contact</a>
</li>
After reading the code, is there anything you think would cause an error to occur?