Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Blade Route Directives
<?php
// Register these inside a service provider:
Blade::directive('route', function ($expression) {
return "<?php echo route({$expression}) ?>";
});
Blade::directive('routeIs', function ($expression) {
return "<?php if (request()->routeIs({$expression})) : ?>";
});
Blade::directive('endrouteIs', function () {
return "<?php endif; ?>";
});
@markvaneijk

This comment has been minimized.

Copy link

@markvaneijk markvaneijk commented Jan 4, 2020

I use these things also often. Works very nice. The second one could be shorter as a custom Blade If:

Blade::if('routeIs', function ($expression) {
    return "<?php if (request()->routeIs({$expression})) : ?>";
});
@matijakovacevic

This comment has been minimized.

Copy link

@matijakovacevic matijakovacevic commented Jan 4, 2020

a small fix to @markvaneijk solution...

For IF directives to work, it has to return boolean instead of a string

Blade::if('routeIs', function ($expression) {
    return request()->routeIs($expression);
});
@markvaneijk

This comment has been minimized.

Copy link

@markvaneijk markvaneijk commented Jan 4, 2020

You’re right, I wrote it too quickly 😅

@matijakovacevic

This comment has been minimized.

Copy link

@matijakovacevic matijakovacevic commented Jan 5, 2020

Copy pasted it, and wondered why it didn't work 😅
(felt like 2000's when I was doing it the same aka script kiddie style)

didn't know of the IF directive though, so thanks for pointing it out! 🤓

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment