How to use Inject View in 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....
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Global Variable for All Views Example
- How to Check If a (Blade) View File Exists in Laravel?
- How to Pass Data from Controller to View in Laravel?
- Laravel Blade Check if Array Key Exists Example
- Laravel Blade Check If Variable Exists or Not Example
- How to use Carbon in Laravel Blade or Controller File?
- How to Call Controller Function in Blade Laravel?
- Laravel Blade @includeWhen and @includeUnless Example
- Laravel Blade Include File If Exists Example
- Laravel Include Blade File with Data Example
- Laravel Blade If Multiple Conditions Example
- Laravel - How to Check If Array is Empty in Blade?
- Laravel Blade Check if View Exists or Not Example