Laravel Blade Include File If Exists Example

In this example we will show laravel blade include file if exists example. I explain step by step how to include file if exists in laravel blade. In this post we will discuss on laravel blade include file if exists example. This example will help you include if file exists laravel blade.

In this example you learn simple example of how to include file if exists in laravel blade. if you require to include file if exists in laravel 6, laravel 7 and laravel 8 then this example will help you.

Read Also :  Laravel Where Like eloquent Query Example

Laravel provide two @include directive. One is @include directive and second is @includeIf directive. If you use @include then if view not exists then it throw error, but if you use @includeIf then it will not throw error. It will only include when it’s exists.

Step 1: Create route

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

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

Step 2: Create controller

In this step we will create UserController.php file for include file if exists in laravel blade. So let’s following code:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
  public function index()
  {
    return view('users');

  }

}

Step 3: Create view

In this step we will create two file. One is users.blade.php file and second is alert.blade.php file.

Read Also :  Laravel Migration Add Comment to Column Example

users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
   
@includeIf('alert', ['type' => 'success'])
    
</body>
</html>

alert.blade.php

<div class="alert alert-{{$type}}">
    This is Alert.
</div>

I hope you understand of Laravel Blade Include File If Exists and it can help you…