Current Location: Home> Latest Articles> Practical Guide: How to Get and Use the Current URL in Laravel’s @if Statement

Practical Guide: How to Get and Use the Current URL in Laravel’s @if Statement

gitbox 2025-06-11

Introduction

Laravel is a free, open-source PHP web framework that follows the MVC pattern. Due to its elegant syntax and simplicity, it is favored by many developers. Laravel uses controllers to manage application logic, which then works with views to generate the final HTML responses presented to users interactively. In development, it’s often necessary to decide what content to display in views based on the current URL, which requires conditional statements like @if.

Getting the Current URL

In PHP, the built-in $_SERVER variable can be used to get the current request URL. Here is a sample code:

$url = $_SERVER['REQUEST_URI'];

This variable contains the current request path and query string. Since the URL might include encoded characters (like %20 for space), you can decode it using rawurldecode:

$url = rawurldecode($url);

@if Statements in Laravel

@if is a commonly used conditional control statement in Laravel views, which renders certain parts of the page depending on the condition’s truth value. For example:

@if ($temperature <= 0)
  The temperature is below freezing. Please stay inside.
@endif

This code displays a message advising users to stay indoors if the temperature is less than or equal to zero.

Getting the Current URL Inside an @if Statement

You can retrieve the current URL inside a PHP block in your view and then use it in an @if condition:

@php
  $url = rawurldecode($_SERVER['REQUEST_URI']);
@endphp

The variable $url now contains the full request path, which can be used in condition checks.

Example

Here is an example demonstrating how to show different content based on the URL:

@php
  $url = rawurldecode($_SERVER['REQUEST_URI']);
@endphp
<p>@if (strpos($url, '/blog/') === 0)<br>
Blog posts<br>
@else<br>
Home page<br>
@endif<br>

This code checks if the current URL starts with "/blog/". If yes, it displays a blog post listing; otherwise, it shows the homepage content.

Conclusion

In Laravel, using $_SERVER['REQUEST_URI'] to get the current URL and combining it with @if conditional statements allows flexible view rendering. Mastering this technique helps dynamically display different pages based on user navigation, enhancing the user experience.