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

netm's avatar
Level 1

Blade::if renders in blade in strange way

I have declared a Blade helper in a Middleware file and the logic works as expected but it also renders part of the code in the browser. I've tried many things but can not figure out why it is doing it! Any help much appreciated.

// In Middleware
Blade::if('isRole', function ($roles = []) use($usersOrgRole) {
  return in_array($usersOrgRole->role, $roles);
});

// In Blade
@isRole(['ORG_ADMIN'])
  <header>...</header>
@endisRole

The above renders the header when it should, but in the browser '@isRole(['ORG_ADMIN'])' is visible before the header and '@endisRole' after.

Another oddness is this happens intermittently in my Sail Dev setup but reliably on Production.

0 likes
6 replies
tykus's avatar

I have declared a Blade helper in a Middleware file

Why in a middleware file, and not a ServiceProvider?

Are you sure this logic is working; have you tried the case where the directive returns false? Is the view template file a Blade template (.blade.php extension)?

netm's avatar
Level 1

@tykus Yes if the logic is working for sure, when it returns false the header is not shown, the weirdness only happens when it is true. And yes def a .blade.php file as it renders all other blade stuff perfectly.

I'll look into ServiceProvider but I had it in Middleware because my logic needed a request URL:: parameter and Auth::user() and I think they are unavailable in ServiceProvider?

tykus's avatar

@netm the directive's Closure is registered, but not evaluated, so you don't actually use the auth user inside the ServiceProvider (assuming you refactor the $usersOrgRole into the Closure).

The other behaviour, I have never experienced outside of the circumstances I described above.

Snapey's avatar

@netm then you totally misunderstand how blade extensions work

a blade extension creates php code that is injected into the view, to be run when the view is processed

This will never work correctly in middleware

netm's avatar
Level 1

Er @tykus could you possibly explain that a bit more - do you mean move the directive to Service Provider and pass the required User and Request parameters I need in to the directive in the blade file?

Please or to participate in this conversation.