How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?
Asked Answered
S

30

350

I am using Laravel 4. I would like to access the current URL inside an @if condition in a view using the Laravel's Blade templating engine but I don't know how to do it.

I know that it can be done using something like <?php echo URL::current(); ?> but It's not possible inside an @if blade statement.

Any suggestions?

Showiness answered 11/7, 2013 at 10:36 Comment(1)
did any answer below help with your issue ?Monotony
I
436

You can use: Request::url() to obtain the current URL, here is an example:

@if(Request::url() === 'your url here')
    // code
@endif

Laravel offers a method to find out, whether the URL matches a pattern or not

if (Request::is('admin/*'))
{
    // code
}

Check the related documentation to obtain different request information: http://laravel.com/docs/requests#request-information

Inebriate answered 11/7, 2013 at 11:14 Comment(9)
<li{{ (Request::is('admin/dashboard') ? ' class="active"' : '') }}> i tried this, failed :xUstulation
In my case I was using a starting / for the URL, removing it would solve the issueGuv
@Inebriate what if I need to put a banner on all the pages except the home page try this not working @if(Request::url()!=='/') <div class="bannerImage">{{ HTML::image('images/fullimage3.jpg') }}</div> @endifGrams
I use the next format for it: <li{!! (Request::url() == url('/')) ? ' class="active"' : '' !!}> , because the format with {{ some_code }} use string encoding.Aerology
url() now returns a builder instance. must use url()->current()Excoriate
@JeffPuckettII Could you provide Laravel version this change is related to? I will add note about this to answer. TY.Inebriate
I'm not sure when it started, but the link I provided is for current 5.4Excoriate
Although I upvoted this a long time ago, today I was having trouble with it on Laravel 5.7 and eventually got this to work instead: @if (Request::path() != 'login'). Notice the lack of slash before "login", too.Contraceptive
This leaves off the query string. Some answers below recommended url()->full(), which includes the query string.Atrocious
P
114

You can also use Route::current()->getName() to check your route name.

Example: routes.php

Route::get('test', ['as'=>'testing', function() {
    return View::make('test');
}]);

View:

@if(Route::current()->getName() == 'testing')
    Hello This is testing
@endif
Pornography answered 8/1, 2015 at 17:36 Comment(6)
FYI, Route::is('testing') is the same as Route::current()->getName() == 'testing'.Wellstacked
@Wellstacked No both are different, Route::is('testing') ->> testing it will not work Route::is('test') ->> test it will work Route::current()->getName() == 'testing' alias and url are differentsFraternal
@Naveen nope, Route::is() checks for the route name, not the path.Wellstacked
also shorthand Route::currentRouteName()Excoriate
@Wellstacked Yeah, but that wouldn't work when working with parameters in your URL, for example, tokens ...Epitome
@Epitome you can use wildcards like Route::is('foo.*) or even Route::is('foo*').Wellstacked
M
77

Maybe you should try this:

<li class="{{ Request::is('admin/dashboard') ? 'active' : '' }}">Dashboard</li>
Mongoloid answered 8/1, 2015 at 14:27 Comment(0)
U
71

To get current url in blade view you can use following,

<a href="{{url()->current()}}">Current Url</a>

So as you can compare using following code,

@if (url()->current() == 'you url')
    //stuff you want to perform
@endif
Unhopedfor answered 24/4, 2017 at 13:51 Comment(4)
If you need to get the query string in the blade as well then you can use request()->getQueryString() which is very helpful in conjunction with url()->current() as that leaves off the query string.Cichlid
``` @if(url()->current() == '/admin/search-result' ``` I used this code but it doesn't work?Taille
@MahdiSafari in that case just write @if(Request::is('admin/search-result'))Unhopedfor
This worked very nicely. ThanksStreptococcus
A
55

I'd do it this way:

@if (Request::path() == '/view')
    // code
@endif

where '/view' is view name in routes.php.

Airlie answered 31/7, 2014 at 21:30 Comment(5)
How to tell if the current dir is home? I mean, public/. Ahh, i got it, i just type =='public'Epitome
If home dir is '/' in route.php, you just write == '/')Airlie
How would you make it work with the parameters as well? Not only the route name.Epitome
You can concatenate parameters in many ways after route name, depending on how you configured your routes.Airlie
I do it like this: Request::url() - than you get the complete URLWhoremaster
U
29

This is helped to me for bootstrap active nav class in Laravel 5.2:

<li class="{{ Request::path() == '/' ? 'active' : '' }}"><a href="/">Home</a></li>
<li class="{{ Request::path() == 'about' ? 'active' : '' }}"><a href="/about">About</a></li>
Unweighed answered 28/7, 2016 at 4:31 Comment(3)
Thank you, I knew the code but Google got me here in 5 seconds haha.Hong
Also this same working with laravel 4.2 and it's working good. Thank youGalloon
Also working on Laravel 5.6, thanks... this just saved me from making navs for each view :DTa
W
20

A little old but this works in L5:

<li class="{{ Request::is('mycategory/', '*') ? 'active' : ''}}">

This captures both /mycategory and /mycategory/slug

Willette answered 17/3, 2016 at 16:6 Comment(1)
I'm using {{ Request::is('clientes/*') ? 'active' : ''}}Leandroleaning
A
18

Laravel 5.4

Global functions

@if (request()->is('/'))
    <p>Is homepage</p>
@endif
Avowed answered 5/5, 2017 at 2:52 Comment(2)
This does not always work if you're dealing with query string like so domain.com/?page_id=1, domain.com/?page_id=2, as those URLs also equal as "/"Untoward
I used request()->routeIs('...')Gustav
C
18

You will get the url by using the below code.

For Example your URL like https//www.example.com/testurl?test

echo url()->current();
Result : https//www.example.com/testurl

echo url()->full();
Result: https//www.example.com/testurl?test
Culminant answered 5/8, 2020 at 14:53 Comment(0)
S
17

You can use this code to get current URL:

echo url()->current();

echo url()->full();

I get this from Laravel documents.

Seismoscope answered 16/12, 2018 at 12:37 Comment(0)
N
15

I personally wouldn't try grabbing it inside of the view. I'm not amazing at Laravel, but I would imagine you'd need to send your route to a controller, and then within the controller, pass the variable (via an array) into your view, using something like $url = Request::url();.

One way of doing it anyway.

EDIT: Actually look at the method above, probably a better way.

Nesline answered 11/7, 2013 at 11:5 Comment(0)
W
14

For me this works best:

class="{{url()->current() == route('dashboard') ? 'bg-gray-900 text-white' : 'text-gray-300'}}"
Whaling answered 1/8, 2020 at 10:49 Comment(0)
P
12

A simple navbar with bootstrap can be done as:

    <li class="{{ Request::is('user/profile')? 'active': '' }}">
        <a href="{{ url('user/profile') }}">Profile </a>
    </li>
Pape answered 15/2, 2016 at 20:30 Comment(0)
M
10

The simplest way is

<li class="{{ Request::is('contacts/*') ? 'active' : '' }}">Dashboard</li>

This colud capture the contacts/, contacts/create, contacts/edit...

Moonseed answered 23/6, 2019 at 9:4 Comment(0)
G
9

The simplest way is to use: Request::url();

But here is a complex way:

URL::to('/').'/'.Route::getCurrentRoute()->getPath();
Genuflect answered 14/7, 2015 at 11:38 Comment(0)
B
9

There are two ways to do that:

<li{!!(Request::is('your_url')) ? ' class="active"' : '' !!}>

or

<li @if(Request::is('your_url'))class="active"@endif>
Blotch answered 7/1, 2016 at 6:32 Comment(0)
V
9

You should try this:

<b class="{{ Request::is('admin/login') ? 'active' : '' }}">Login Account Details</b>
Vina answered 30/6, 2018 at 10:18 Comment(0)
M
8

For named routes, I use:

@if(url()->current() == route('routeName')) class="current" @endif
Mckee answered 7/2, 2019 at 19:42 Comment(0)
C
7

Set this code to applied automatically for each <li> + you need to using HTMLBuilder library in your Laravel project

<script type="text/javascript">
    $(document).ready(function(){
        $('.list-group a[href="/{{Request::path()}}"]').addClass('active');
    });
</script>
Chorion answered 18/11, 2016 at 17:42 Comment(0)
A
7
class="nav-link {{ \Route::current()->getName() == 'panel' ? 'active' : ''}}"
Argue answered 22/2, 2019 at 20:11 Comment(0)
C
7

In Blade file

@if (Request::is('companies'))
   Companies name 
@endif
Cota answered 12/10, 2019 at 9:15 Comment(0)
A
7

1. Check if URL = X

Simply - you need to check if URL is exactly like X and then you show something. In Controller:

if (request()->is('companies')) {
  // show companies menu or something
}

In Blade file - almost identical:

@if (request()->is('companies'))
  Companies menu
@endif

2. Check if URL contains X

A little more complicated example - method Request::is() allows a pattern parameter, like this:

if (request()->is('companies/*')) {
  // will match URL /companies/999 or /companies/create
}

3. Check route by its name

As you probably know, every route can be assigned to a name, in routes/web.php file it looks something like this:

Route::get('/companies', function () {
  return view('companies');
})->name('comp');

So how can you check if current route is 'comp'? Relatively easy:

if (\Route::current()->getName() == 'comp') {
  // We are on a correct route!
}

4. Check by routes names

If you are using routes by names, you can check if request matches routes name.

if (request()->routeIs('companies.*')) {
  // will match routes which name starts with companies.
}

Or

request()->route()->named('profile')

Will match route named profile. So these are four ways to check current URL or route.

source

Ankledeep answered 14/12, 2022 at 2:31 Comment(1)
The question is about Laravel 4, and this is based on a tutorial for Laravel 9. Request::is('companies') is how it's done in Laravel 4.Roband
C
6

instead of using the URL::path() to check your current path location, you may want to consider the Route::currentRouteName() so just in case you update your path, you don't need to explore all your pages to update the path name again.

Chalcography answered 30/11, 2017 at 14:14 Comment(0)
S
4

Another way to write if and else in Laravel using path

 <p class="@if(Request::is('path/anotherPath/*')) className @else anotherClassName @endif" >
 </p>

Hope it helps

Snakebird answered 5/9, 2017 at 6:42 Comment(0)
A
2

Try this:

@if(collect(explode('/',\Illuminate\Http\Request::capture()->url()))->last() === 'yourURL')
    <li class="pull-right"><a class="intermitente"><i class="glyphicon glyphicon-alert"></i></a></li>
@endif
Avivah answered 28/9, 2018 at 17:13 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.Hackery
T
2

For Laravel 5.5 +

<a class="{{ Request::segment(1) == 'activities'  ? 'is-active' : ''}}" href="#">
                              <span class="icon">
                                <i class="fas fa-list-ol"></i>
                              </span>
                            Activities
                        </a>
Tinsel answered 25/3, 2021 at 16:51 Comment(0)
H
1
@if(request()->path()=='/path/another_path/*')
@endif
Hindward answered 22/2, 2018 at 7:2 Comment(1)
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.Alejandraalejandrina
F
1

There are many way to achieve, one from them I use always

 Request::url()
Foothill answered 7/3, 2018 at 5:29 Comment(0)
S
1

Try This:

<li class="{{ Request::is('Dashboard') ? 'active' : '' }}">
    <a href="{{ url('/Dashboard') }}">
	<i class="fa fa-dashboard"></i> <span>Dashboard</span>
    </a>
</li>
Supraliminal answered 25/3, 2018 at 12:45 Comment(0)
K
0

Try this way :

<a href="{{ URL::to('/registration') }}">registration </a>
Kr answered 12/4, 2018 at 12:25 Comment(1)
Add some explanation to your answerBeulahbeuthel

© 2022 - 2024 — McMap. All rights reserved.