Common Usage of isset php function in laravel

According to php official documentation

isset php function can be used to determine if a variable is declared and is different than NULL. If a variable has been unset with the unset() function, it is no longer considered to be set.

In the context of laravel, we can use isset php function for general purpose as well as special purpose. Here are the some usage of this function.

Availability of Shared Variables
In laravel, we can share variables accross multiple views in the frontend. We need to share variables when we need dynamic content in the most commonly in header, footer or sidebar. We have already discussed the process of sharing variables to the views.
Also Read: How to create custom helper function in laravel ?
For example, we need dynamically generated nav bar where nav bar items will be generated based on value of a php variable. In this case, only if some variable is set and is not null, we have to show nav item.
        <li class="nav-item">
                <a class="nav-link" href="{{url('/about')}}">About</a>

In above example, we just check if we have  a not null variable $about, we will display the nav item about.

Checking Existance of Object Properties

We can determine if object has certain properties using isset php function. It works in nested structure as well when we have sequence of properties.

// Declare an item as object variable.

$item = (object) array("price" => 200);

// Checking if item has some property price

isset($item->price)  => true

// Checking another property

isset($item->size) => false

In above example, item has price but not size. We can use isset to check if object has certain property or not. We can use isset php function for nested properties as well.

// Check if item has size and width

isset($item->size->width) => false

This will result false since we dont have any size property.

Checking if array has some key with not null value
We can use isset php function to check if a variable has certain key and not null value in it.
$array = ['price' => 100, 'size' => '400x400', 'weight' => 3.5];

echo isset($array['color']);

Output of the above code will be false since there is no array key called 'color' in array.

share :

Sagar Gautam

A Computer Engineer from Nepal.

Leave your Feedback