ItSolutionStuff.com

How to use Inject View in Laravel?

By Hardik Savani • November 5, 2023
Laravel

Nowdays, Laravel is a very popular framework, it has a lots of function and that's why always choose this. In this post you can learn how to use and why we should use inject view, Laravel 5 introduce blade inject view that way you can make your own view file that file will not depend any variable, controller or view, that means like widget.

Why we should use blade inject in our project, so if we work on front-end project and we always print categories on left side, i mean in every page so we always share $categories variable for listing. But If we include inject view that way we don't need to always share $categories variable, because inject through you can access direct class methods.

In bellow example i did same, i created Category Model that will return category. It has one getCategory() that returns all lists of category, overthere you can also use query builder. Other i create new blade file using inject that always return all category listed with good layout, you can create inject variable using @inject. So, first craete Category model.

app/Category.php

namespace App;


class Category

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

public function getCategory()

{

return ['PHP','Laravel','Jquery','Json','AngularJS','Ubuntu'];

}

}

Ok, now create new view file in your views folder and copy paste bellow code.

resources/views/myinject.php

@inject('category','App\Category')


<h2>Categories</h2>


<ul>

@foreach($category->getCategory() as $value)

<li>{{ $value }}</li>

@endforeach

</ul>

Ok, now you are ready to your widget anyway, it will always return all listed categories with proper layout. You can include it anyway this way.

@include('myinject')

Try this....

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Global Variable for All Views Example

Read Now →

How to Check If a (Blade) View File Exists in Laravel?

Read Now →

How to Pass Data from Controller to View in Laravel?

Read Now →

Laravel Blade Check if Array Key Exists Example

Read Now →

Laravel Blade Check If Variable Exists or Not Example

Read Now →

How to use Carbon in Laravel Blade or Controller File?

Read Now →

How to Call Controller Function in Blade Laravel?

Read Now →

Laravel Blade @includeWhen and @includeUnless Example

Read Now →

Laravel Blade Include File If Exists Example

Read Now →

Laravel Include Blade File with Data Example

Read Now →

Laravel Blade If Multiple Conditions Example

Read Now →

Laravel - How to Check If Array is Empty in Blade?

Read Now →

Laravel Blade Check if View Exists or Not Example

Read Now →