Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Laravel Error: How to solve undefined variable or null value using isset directive

The isset function in PHP is used to determine if a variable is set and is not null. It returns true if the variable is set and has a value other than null, and false otherwise. This function is commonly used to check the existence of variables before using them to avoid "Undefined variable" errors and to handle input validation and form submissions. Here are some common use cases for the isset function:
Checking if a variable is set:
Handling form submissions:
Checking if array keys exist:
Checking if a session variable is set:
you can use common sidebar,navbar
validation specific input field exists in the request data
validating whether a session variable is set or not.
Checking if a variable is set:
How to use explode in different format of data
use of explode with isset funtion on splitted data using explode

if (isset($variable)) {
    // $variable is set and not null, you can use it here
} else {
    // $variable is not set or is null
}
Enter fullscreen mode Exit fullscreen mode

Handling form submissions:

if (isset($_POST['submit_button'])) {
    // Form has been submitted, process the data
    $username = $_POST['username'];
    $password = $_POST['password'];
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Checking if array keys exist:

$myArray = array('name' => 'John', 'age' => 30);
if (isset($myArray['name'])) {
    // 'name' key exists in the array
} else {
    // 'name' key does not exist
}
Enter fullscreen mode Exit fullscreen mode

Checking if a session variable is set:

session_start();
if (isset($_SESSION['user_id'])) {
    // User is logged in, perform authorized actions
} else {
    // User is not logged in
}
Enter fullscreen mode Exit fullscreen mode

Checking if a variable is set within a function:

function myFunction($param) {
    if (isset($param)) {
        // $param is set and not null within the function
    } else {
        // $param is not set or is null within the function
    }
}

    }
}

Enter fullscreen mode Exit fullscreen mode

Using isset is a good practice to ensure that your code behaves predictably and avoids errors related to undefined or null variables. It helps you handle input validation and perform actions based on the presence of variables or array keys.

  <!-- {{-- add here profile label start --}} -->
    @isset($getting_roll_id)
    @if ($getting_roll_id ==1)
    <span style="margin-left: 44px;">
      <button type="button" class="btn btn-light mt-2" style=""><i class="fa fa-shield" aria-hidden="true">&nbsp;&nbsp;
          Admin</span>
    </i> &nbsp;&nbsp;
    </button>

    @elseif ($getting_roll_id ==2)
    <span style="margin-left: 44px;">
      <button type="button" class="btn btn-info mt-2" style=""><i class="fa fa-shield" aria-hidden="true">&nbsp;&nbsp;
          Manager</span>
    </i> &nbsp;&nbsp;
    </button>
    @else
    <span style="margin-left: 44px;">
      <button type="button" class="btn btn-light mt-2" style=""><i class="fa fa-shield" aria-hidden="true">&nbsp;&nbsp;
          User</span>
    </i> &nbsp;&nbsp;
    </button>
    @endif
    @else
    <!-- Handle the case where $getting_roll_id is not present -->
    <p></p>
     @endisset
Enter fullscreen mode Exit fullscreen mode

validation specific input field exists in the request data

use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index()
    {
        return view('contact');
    }

    public function submit(Request $request)
    {
        // Check if the 'email' field exists in the request
        if (isset($request->email)) {
            // Validation rules
            $rules = [
                'email' => 'required|email',
            ];

            // Validation messages
            $messages = [
                'email.required' => 'The email field is required.',
                'email.email' => 'The email must be a valid email address.',
            ];

            // Validate the request data
            $request->validate($rules, $messages);

            // Validation passed, perform further actions
            return "Validation passed. Email: " . $request->input('email');
        } else {
            // 'email' field is not present in the request
            return "Email field is missing.";
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
</head>
<body>
    <form method="POST" action="/contact">
        @csrf
        <label for="email">Email:</label>
        <input type="text" name="email" id="email">
        <button type="submit">Submit</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

validating whether a session variable is set or not.
In Laravel, the isset function can be useful for validating whether a session variable is set or not. This can help you determine if a user is authenticated or if certain session data exists before allowing them to access specific routes or perform certain actions. Here's an example of how to use isset for session variable validation in Laravel with example code and expected output:

use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        // Check if the 'user_id' session variable is set
        if (isset($request->session()->get('user_id'))) {
            // User is authenticated, allow access to the dashboard
            return view('dashboard');
        } else {
            // User is not authenticated, redirect to the login page
            return redirect('/login');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Create a view file for the dashboard (e.g., dashboard.blade.php):

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome to the Dashboard</h1>
    <!-- Dashboard content goes here -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In your login logic, set the "user_id" session variable when a user successfully logs in. For example, in your login controller:

use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
public function login(Request $request)
{
// Perform login logic here

    // If login is successful, set the 'user_id' session variable
    Session::put('user_id', $userId);

    // Redirect to the dashboard
    return redirect('/dashboard');
}
Enter fullscreen mode Exit fullscreen mode

}
In this example, the isset function is used to check if the "user_id" session variable is set. If it's set, the user is considered authenticated, and they are allowed to access the dashboard view. If it's not set, the user is redirected to the login page.

Output:

If a user successfully logs in, the "user_id" session variable will be set, allowing them to access the "/dashboard" route and see the dashboard content.
If a user is not logged in or has not set the "user_id" session variable, they will be redirected to the login page or a page of your choice.

Another use
you can use common sidebar,navbar

How to use explode in different format of data

get the data after spliting string using explode
get data through issets condition to avoid error if not data present initially empty database
apply if-else condition to match requirment on getting data

  @php
                        $parts = explode(':', $item->addcarts);
                        $valueAfterColon = isset($parts[1]) ? $parts[1] : null;
                          @endphp
                          @if (($parts[1] == 'yes') && (auth()->user()->email == $parts[0]))  

                            <button type="submit"  
                             class="btn btn-sm  btn-primary" style="position: relative;float:right">Added</button> 
                            @else
                            <button type="submit"  
                             class="btn btn-sm  btn-primary addToCartBtn" data-item-id="{{ $item->id }}"  style="position: relative;float:right">Add To Cart</button> 
                            @endif 
Enter fullscreen mode Exit fullscreen mode

apply explode function json data format

 [{"field1":"value1","field2":10,"created_at":"2022-01-01 12:30:00"},
 {"field1":"value2","field2":20,"created_at":"2022-01-02 14:45:00"}]
Enter fullscreen mode Exit fullscreen mode
$jsonData = '[{"field1":"value1","field2":10,"created_at":"2022-01-01 12:30:00"},
 {"field1":"value2","field2":20,"created_at":"2022-01-02 14:45:00"}]';

// Decode JSON string to PHP array
$dataArray = json_decode($jsonData, true);

// Loop through each element in the array
foreach ($dataArray as $item) {
    // Access individual elements
    $field1 = $item['field1'];
    $field2 = $item['field2'];
    $createdAt = $item['created_at'];

    // Split the values of a specific string using explode
    $createdAtParts = explode(' ', $createdAt);

    // Output or use the values as needed
    echo "Field1: $field1, Field2: $field2, Created At: $createdAt\n";
    echo "Created Date: {$createdAtParts[0]}, Created Time: {$createdAtParts[1]}\n";
}
Enter fullscreen mode Exit fullscreen mode

Apply explode on array data

$emailArray = ["john@example.com", "jane@example.com"];

foreach ($emailArray as $email) {
    // Use explode to split the email address at the "@" symbol
    $parts = explode('@', $email);

    // Access the part before the "@" symbol
    $username = $parts[0];

    // Output or use the extracted username as needed
    echo "Email: $email, Username: $username\n";
}
Enter fullscreen mode Exit fullscreen mode

use of explode with isset funtion on splitted data using explode

$jsonData = '[{"field1":"value1","field2":10,"created_at":"2022-01-01 12:30:00"},
 {"field1":"value2","field2":20,"created_at":"2022-01-02 14:45:00"}]';

// Decode JSON string to PHP array
$dataArray = json_decode($jsonData, true);

// Loop through each element in the array
foreach ($dataArray as $item) {
    // Use isset to check if the keys exist
    $field1 = isset($item['field1']) ? $item['field1'] : null;
    $field2 = isset($item['field2']) ? $item['field2'] : null;
    $createdAt = isset($item['created_at']) ? $item['created_at'] : null;

    // Split the values of a specific string using explode
    $createdAtParts = explode(' ', $createdAt);

    // Output or use the values as needed
    echo "Field1: $field1, Field2: $field2, Created At: $createdAt\n";

    // Check if the array has the expected structure before accessing its elements
    if (isset($createdAtParts[0]) && isset($createdAtParts[1])) {
        echo "Created Date: {$createdAtParts[0]}, Created Time: {$createdAtParts[1]}\n";
    } else {
        echo "Invalid data structure for Created At\n";
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)