Laravel - check if routes on blade
Asked Answered
J

5

14

I need to check 2 routes, and if one is true, add some content

@if (Route::current()->uri() != '/' || Route::current()->uri() != 'login')<div>add some content some contnt </div> @endif

I have tried with '||' and 'OR' and 'or'. I have also tried with Request::path(), which works only when checking 1 route

@if (Route::current()->uri() != '/') <div>add some content some contnt </div> @endif

If I try 2 routes it doesn't seem to work

Jerricajerrie answered 3/2, 2020 at 22:20 Comment(1)
the if statement looks fine to me. Should work. Please note that you are checking if NOT root or if NOT login. What is the URL shown in your address bar when you observed it was not working?Budde
D
39

You can use the built in methods to check for a route name or pattern.

See Route::is() or Route::currentRouteNamed()

For example:

Route::get('users', 'Controller..')->name('users.index');
Route::get('users/{id}', 'Controller..')->name('users.show');

Assuming you are in the following path : users/1

@if(Route::is('users.show') )
    // true
@endif

@if(Route::is('users') )
    // false
@endif

@if(Route::is('users.*') )
    // true
@endif

So in your example try @if(Route::is('home') or Route::is('login'))..@endif

Dismay answered 8/10, 2020 at 17:16 Comment(2)
It should be Route::currentRouteName() instead of Route::currentRouteNamed().Wallie
You could also use currentRouteName but the difference is that this method returns a string (route name) or null, on the other hand, currentRouteNamed accepts argument of patterns and returns a boolean. github.com/illuminate/routing/blob/…Dismay
M
7

You could also do:

request()->routeIs('categories') or request()->routeIs(['categories', 'services'])

Modiolus answered 6/1, 2021 at 12:57 Comment(0)
S
4

Try using route names instead. In your web.php file put this:

Route::get('/')->name('home');
Route::get('/login')->name('login');

And then change your if condition to this:

@if (Route::currentRouteName() != 'home' || Route::currentRouteName() != 'login')
<div>add some content some contnt </div> 
@endif
Spaniel answered 4/2, 2020 at 0:15 Comment(0)
A
3

You need to make your condition right because you're comparing between url and string. Try this plz:

URL::current() != url('/')

Anh answered 3/2, 2020 at 23:6 Comment(0)
B
1

I'd use routes names and in_array instead...

In your web.php

Route::get('/', ...)->name('home');
Route::get('/login', ...)->name('login');

Then you can do something like this

in_array(Route::currentRouteName(), ['home', 'login'])
Balduin answered 3/2, 2020 at 23:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.