Category : #laravel
Tags : #laravel, #laravel blade template
Sometimes we need to print data in our blade file from our service class in laravel. In this case, we can do it in many ways. But laravel provides @inject
blade directive to do that very easily. So in this tutorial, you will learn how to use class in blade laravel.
The @inject
directive is used to retrieve a service from the Laravel service container. The first argument passed to @inject
is the name of the variable the service will be placed into, and the second argument is the class or interface name of the service which you wish to resolve:
See the example of how we can implement laravel blade inject example:
app/Utils/Utils.php
<?php
namespace App\Utils;
class Utils
{
public function getStringToUpperCase(string $string) : string
{
return strtoupper($string);
}
}
And after creating this service, we can call this function in our blade file like:
resources/views/welcome.blade.php
@extends('layouts.app')
@inject('utils', 'App\Utils\Utils')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Laravel 9.x Service Injection Tutorial | Laravelia</div>
<div class="card-body">
{{ $utils->getStringToUpperCase('laravelia') }}
</div>
</div>
</div>
</div>
</div>
@endsection
Read also: How To Use @Stack And @Push Blade Directive In Laravel
Conclusion
I have tried to discuss the clear concept of blade inject in laravel. Now we know how to laravel use class in view. Hope this how to use class in blade laravel will help you.