htclog81
htclog81

Reputation: 167

laravel access to model constant in blade

I want to access a class constant in a Blade file without using the full path:

class PaymentMethod extends Model
{
    const PAYPAL_ACCOUNT = 'paypal_account';
    const CREDIT_CARD    = 'credit_card';
}

In my blade file this works:

{{ App\Classes\Models\PaymentMethod::CREDIT_CARD }}

...but this throws Class 'PaymentMethod' not found

{{ PaymentMethod::CREDIT_CARD }}

Is there a less verbose way to access this constant?

Upvotes: 11

Views: 14301

Answers (3)

Mast__G
Mast__G

Reputation: 53

Constants in the Model issue

Coupling constants in model and refrencing them in the view is a bad practice. Laravel has option to create constants in seaprate file.

Way of the Constants folder

You have Constants folder. Create file in it - eg. Constants/Payment.php

class Payment
{
    const PAYPAL_ACCOUNT = 'paypal_account';
    const CREDIT_CARD    = 'credit_card';
}

Then in you controller access it

use App\Constants\Payment AS PaymentConstants;
    // ...
    $creditCard = PaymentConstants::CREDIT_CARD;
    // ...
    return view('view.name', compact('creditCard'));

In blade template:

// {{ PaymentMethod::CREDIT_CARD }}
{{ $creditCard }}

Way of the Config folder

Alternative is to use config file, create yours there like config/payment.php

<?php

return [
    'PAYPAL_ACCOUNT' => 'paypal_account';
    'CREDIT_CARD'    => 'credit_card';
];

in blade template:

{{ config('payment.CREDIT_CARD') }}

Config version comes with a small performance overhead (load&parsed @ runtime)

Upvotes: 0

Andrius Rimkus
Andrius Rimkus

Reputation: 653

Found this thread while trying to solve the same problem. Decided to go with injecting the class:

namespace App\Services\Auth\IAM;

class IAMConstants
{
    const GUARD_WEB = 'web';
    const GUARD_ADMIN = 'admin';
}

Then in Blade:

@inject('constants', 'App\Services\Auth\IAM\IAMConstants')
...
<option value="{{ $constants::GUARD_WEB }}">App user</option>

The injected class should be small since it will carry in all its dependencies.

Upvotes: 9

ABDEL-RHMAN
ABDEL-RHMAN

Reputation: 3014

You may use aliases:

in your config\app.php under aliases section :

aliases => [
     ....
    'PaymentMethod' => App\Classes\Models\PaymentMethod::class
]

then use it in your blade file

{{ PaymentMethod::CREDIT_CARD }}

Upvotes: 24

Related Questions