Laravel 5.2 - Service Injection in view template with example
In this tutorial, I am going to tell you how to inject service directly into your views.
There are various situation where you need to use this technique.
@inject
directive is helpful directive to retrieve a service from the Laravel service container.
You will have to pass two argument in @inject
, first is variable name and second argument is your service or interface class name.
Imaginate you have some kind of class in your system, for example i have a class that return total number of category on the site.
So for this, we have created a class called 'Stats.php' that have a function to return total number of category.
app/Stats.php
- <?php
- namespace App;
- class Stats
- {
- public function totalCategory(){
- return 10;
- //you can write here your db query as per your need.
- }
- }
Ok so we have service class here and now let's imaginate we want to use this with our view.
As we know on fresh installation, we have welcome view so we are going to start there.
In bottom of welcome.blade.php
, we include a view file called stats.blade.php
.
- <body>
- <div class="container">
- <div class="content">
- <div class="title">Laravel 5</div>
- </div>
- </div>
- @include('stats')
- </body>
So create a view stats.blade.php
in following path resources/views/.
Example 1 to inject service method in your view using @inject directive
This is first example to inject service in view.
resources/views/stats.blade.php
- @inject('stats', 'App\Stats')
- <div>
- Total Category: {{ $stats->totalCategory() }}.
- </div>
Example 2 to inject service method in your view from routes file
resources/views/stats.blade.php
- <div>
- Total Category: {{ $stats->totalCategory() }}
- </div>
- Route::get('/', function (App\Stats $stats) {
- return view('welcome',compact('stats'));
- });
This was a pretty example where we pass objects of Stats class in view.
Example 3 to inject service method using view composer
If you have an any experience with Laravel you know the one solution is to create a view composer. When you composing this view with view portion then it has set of data.
resources/views/stats.blade.php
- <div>
- Total Category: {{ $stats->totalCategory() }}
- </div>
- View::composer('stats',function($view){
- $view->with('stats',app('App\Stats'));
- });