How to use inject view in Laravel 5?

By Hardik Savani | June 15, 2016 | | 1097 Viewer | Category : Laravel


Share this post:

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....