Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There a Way to Import PHP Classes into a Blade Template and Use Them in Child Templates?

I want to use the cknow/laravel-money package in pretty much every page in my app. I thought a tidy way to do this would be to import the class in the parent blade. However, child templates do not seem to have access to the imported class.

I've tried using standard <?php ?> tags and @php @endphp directives.

app.blade.php

@php
use Cknow\Money\Money; 
@endphp

    <title>{{ config('app.name') }}</title>

    </head>
    <body>
        @include('inc.navbar')
        @include('inc.flashmessages')
        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

show.blade.php

<div class="card-footer text-muted">
    {{ Money::GBP($item->price) }}
</div>

This throws.

"Class 'Money' not found."

Whereas including the same use statement in the child class works as expected.

like image 714
kup_ Avatar asked Jan 27 '19 22:01

kup_


People also ask

Can we write PHP code in blade template Laravel?

Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.

Can I use blade template without Laravel?

You could download the class and start using it, or you could install via composer. It's 100% compatible without the Laravel's own features (extensions).

What is the advantage of Laravel blade template?

The blade templates are stored in the /resources/view directory. The main advantage of using the blade template is that we can create the master template, which can be extended by other files.


1 Answers

You can write it using full path from child template.

\Cknow\Money\Money::GBP($item->price);

If you just want to use Money instead of a full path, you can create an alias from config/app.php file.

like image 78
arvernester Avatar answered Sep 24 '22 13:09

arvernester