Abdallah Sakre
Abdallah Sakre

Reputation: 915

Request path is not working properly in Laravel 5.2

I'm trying to use the following if condition to show something only if the current page is 'results.blade.php' :

@if(Request::path() === 'results')
    <p> results page </p>
@else
     <p> Other page </p>
@endif

The following is the results path :

C:\xampp\htdocs\sharp\resources\views

The output is always "Other page" , even if the opened page was 'results' page.

The following is the route :

Route::get('/search', [
    'uses' => 'SearchController@getResults',
    'as' => 'results'
]);

Upvotes: 1

Views: 544

Answers (2)

user8034901
user8034901

Reputation:

You're confusing the url/path part with the name of the route. Change your code to

@if(Request::path() === 'search')
    <p> results page </p>
@else
     <p> Other page </p>
@endif

and everything should work as expected.

From the documentation:

"The path method returns the request's URI."

The URI part of your route is "/search" (which could also be written as search). The name of that route is "results" which is used to reference that URI: return route('results'); will output "http://localhost:8000/search"

Edit: Routes with parameters:

If you have a route

Route::get('/user/{uid}', [
    'uses' => 'UserController@show',
    'as' => 'userprofile'
]);

you can check for a specific user route (http://localhost/user/3) using:

@if ( Request::path() == 'user/3')
<p>User Profile 3</p>
@else
<p>NOT User Profile 3</p>
@endif

If you want to check any user route (http://localhost/user/1, http://localhost/user/2 ...) use the name of the route:

@if ( Request::route()->getName() == 'userprofile')
<p>User Profile</p>
@else
<p>NOT User Profile</p>
@endif

Upvotes: 2

farooq
farooq

Reputation: 1673

So I tested your code in my laravel project . And for me it is working fine . You forgot to post your SearchController code here .

The problem is you are mentioning the route using two different names . You should use the same name in get('/search') and in 'as'=>'search' ,

in my web.php file,

Route::get('/search', [
    'uses' => 'SearchController@getResults',
    'as' => 'search'
]);

In my SearchController I just redirecting the route to view file .

public function getResults() {
    return view('results');

}

and in my results.blade.php , I used the same code as yours :

@if(Request::path() === 'search')
    <p> search page </p>
@else
     <p> Other page </p>
@endif

I hope this will be helpful .

Upvotes: 1

Related Questions