How to Use @inject in Blade in Laravel 5.1

Access all tutorials in sprocket icon.

June 12, 2015 from author Bill Keck.

In a previous tutorial, we looked at creating a laravel service provider for Laravel. A service provider is a beautiful aspect of the Laravel architecture, but in some cases, when you want to re-use a class in your views, you don’t need it.

Instead, you can use the @inject method in blade. It could work like this:



@section('content')

@inject('boom', 'App\Helpers\Contracts\RocketShipContract')

    {{ $boom->blastOff() }}

@endsection

Ok, so @section and @endsection are typical blade syntax to define where in the master page the ‘content’ will be placed. Then we can see we have the @inject method. The first parameter is the name of the local variable to hold the object, in this case I called it boom. You can call yours any name that falls within variable naming rules.

The next parameter is the class or contract you are instantiating. In this case, I’m calling a contract, because I have a service provider binding the contract to a concrete class. You can refer to that service provider tutorial for the exact reference.

Then in the dual curly brackets, which is again blade syntax to echo php, you see we are calling the blastOff method from the object instance variable $boom. The blastOff method simply returns a string of text. If you are curious why I chose boom, blastOff, and RocketShipContract, these were examples I was using in my service provider tutorial, which is a related subject. Check that out when you have a chance.

There’s an interesting example of @inject in a Laracast’s video where they use stats as an example, which is perhaps a closer to a real-world example.

Anyway, @inject offers you an easy alternative to service providers, allowing you to bring in reusable code that is not tied to a controller. As I’ve explained above, you can also use @inject in tandem with a service provider, when you want to call a contract instead of a concrete class.

Also note that you can place @inject outside of the @section where the object is being used. So if you want to perhaps place it at the top of the file, above the @extends line, you could do so. That might be more intuitive.


@inject('boom', 'App\Helpers\Contracts\RocketShipContract')

@extends('layouts.master')

@section('content')

    {{ $boom->blastOff() }}

@endsection

This looks really clean to me. That kind of flexibility is yet another reason to love the Laravel Framework.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

Advertisements