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

3

12

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.

Ascocarp answered 27/1, 2019 at 22:34 Comment(0)
M
18

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.

Mnemonic answered 27/1, 2019 at 22:42 Comment(1)
Upvoted for: "you can create an alias from config/app.php file." Thanks!Dismast
D
5

Sharing classes with views isn't really the Laravel way of doing this. Typically, all logic should be within the controller and the data passed into the view.

That being said, you could pass the class into every view manually or you could refer to the docs as Laravel Money has Blade extensions built in. Perhaps this provides all the functionality you need?

As per the Laravel Money docs

@currency('USD')
@money(500) // To use default currency present in `config/money.php`
@money(500, 'USD')

// Aggregation
@money_min(@money(100, 'USD'), @money(200, 'USD'), @money(300, 'USD')) // Money::USD(100)
@money_max(@money(100, 'USD'), @money(200, 'USD'), @money(300, 'USD')) // Money::USD(300)
@money_avg(@money(100, 'USD'), @money(200, 'USD'), @money(300, 'USD')) // Money::USD(200)
@money_sum(@money(100, 'USD'), @money(200, 'USD'), @money(300, 'USD')) // Money::USD(700)

// Parsers
@money_parse('$5.00') // Money::USD(100)
@money_parse_by_bitcoin("\xC9\x830.41") // Money::XBT(41000000)
@money_parse_by_decimal('1.00', 'USD') // Money::USD(100)
@money_parse_by_intl('$1.00') // Money::USD(100)
@money_parse_by_intl_localized_decimal('1.00', 'USD') // Money::USD(100)
Diver answered 27/1, 2019 at 22:55 Comment(0)
B
1

views are not suppose to be cluttered with php code

however to solve this, what you can do is define an alias in the config/app.php, add a new line in the aliases array

'Cknow' => Cknow\Money\Money;
Blazon answered 23/11, 2022 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.