Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the Current URL inside the @if Statement in Laravel?
In Laravel, you can access the current URL within Blade template @if statements using several built-in methods. These methods help you conditionally display content based on the current route or URL.
Using Request::path()
The Request::path() method returns only the path portion of the URL (without domain)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
public function index(Request $request) {
return view('test');
}
}
The test.blade.php file
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Nunito', sans-serif;
}
</style>
</head>
<body class="antialiased">
<div>
@if (Request::path() == 'users')
<h1>The path is users</h1>
@endif
</div>
</body>
</html>
The Request::path() method returns the current URL path being used, making it ideal for path-based comparisons.
Using url()->current()
The url()->current() method returns the complete current URL including the domain
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Nunito', sans-serif;
}
</style>
</head>
<body class="antialiased">
<div>
@if (url()->current() == 'http://localhost:8000/users')
<h1>The path is users</h1>
@endif
</div>
</body>
</html>
The path is users
Using Request::url()
The Request::url() method works similarly to url()->current() and returns the full URL
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Nunito', sans-serif;
}
</style>
</head>
<body class="antialiased">
<div>
@if (Request::url() == 'http://localhost:8000/users')
<h1>The path is users</h1>
@endif
</div>
</body>
</html>
The path is users
Using Request::is()
The Request::is() method is the most flexible approach, supporting wildcard patterns
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: 'Nunito', sans-serif;
}
</style>
</head>
<body class="antialiased">
<div>
@if (Request::is('users'))
<h1>The path is users</h1>
@endif
</div>
</body>
</html>
The Request::is() method returns true if the current path matches the given pattern. It also supports wildcards like Request::is('admin/*').
The path is users
Comparison
| Method | Returns | Use Case |
|---|---|---|
Request::path() |
Path only | Simple path comparisons |
url()->current() |
Full URL | Complete URL matching |
Request::url() |
Full URL | Complete URL matching |
Request::is() |
Boolean | Pattern matching with wildcards |
Conclusion
Use Request::is() for most cases as it's cleaner and supports patterns. Choose Request::path() when you only need the path portion, and url()->current() or Request::url() when you need the complete URL for comparison.
