Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel access to model constant in blade

Tags:

php

laravel

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?

like image 242
htclog81 Avatar asked Nov 13 '17 18:11

htclog81


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 }}
like image 143
ABDEL-RHMAN Avatar answered Sep 22 '22 22:09

ABDEL-RHMAN


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.

like image 33
Andrius Rimkus Avatar answered Sep 23 '22 22:09

Andrius Rimkus