Reputation: 167
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
Reputation: 53
Coupling constants in model and refrencing them in the view is a bad practice. Laravel has option to create constants in seaprate file.
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 }}
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
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
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