How to use Inject View in Laravel?

By Hardik Savani November 5, 2023 Category : 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.


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.





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

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



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.


Try this....

Tags :