laravel access to model constant in blade

Viewed 11413

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?

2 Answers

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 }}

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.

Related