Check in Blade File if the Variable is Empty in Laravel

29-Nov-2022

.

Admin

Check in Blade File if the Variable is Empty in Laravel

Hello Friends,

I will explain a step-by-step tutorial check-in blade file if a variable is empty in laravel. This tutorial will give you a simple example of how to check in the blade file if a variable is empty in laravel. I want to show you the laravel check in the blade file if a variable is empty or not example. I explained simply how to check if a variable is empty in laravel blade.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have to follow the below step and you will get the layout as below:

Step 1: Install Laravel


This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Format Route

web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\EmptyVariableController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('/index',[EmptyVariableController::class, 'index']);

Step 3: Create EmptyVariableController

we will create EmptyVariableController. so you can see the below code with output:

php artisan make:controller EmptyVariableController

App\Http\Controllers\EmptyVariableController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class EmptyVariableController extends Controller

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function index()

{

$data = null;

return view('index', compact('data'));

}

}

Step 4: Create Blade File index.blade.php

resources/views/index.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Check in Blade File if Variable is Empty in Laravel: NiceSnippets.com</title>

</head>

<body>

@if(empty($data))

{{ dd('It\'s an empty variable') }}

@else

{{ dd('It\'s not an empty variable') }}

@endif

</body>

</html>

Step 5: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/index

Output:

"It's an empty variable" // resources/views/index.blade.php

I hope it can help you...

#Laravel