Laravel: How to access class constants from a blade template

Viewed 3401

I use lots of class constants in my models. When I want to use them inside blade I start by importing them at the top of the template.

For example:

@php
    use App\Model\Core\User;
@endphp

Later on in the template I use them as shown in the following example.

<option value="@php echo User::MY_CONSTANT @endphp">This is an option</option>

Is there a more elegant way to go about this? It seems a bit crude to directly import a namespace into a variable scope that is managed by a templating engine. My IDE (phpstorm) sure doesn't like it.

2 Answers

I accomplish this by using the PHP constant function. Since blade allows you to call any PHP function directly, you can access any public class constant via this function without importing anything into your view. So, your example would look like this:

<option value="{{ constant('App\Model\Core\User::MY_CONSTANT') }}">This is an option</option>

IDE Note: Since you mention that you use PhpStorm, the only downsides to this solution are that PhpStorm won't inspect the FQCN string you pass to the constant function, so it won't help auto-complete the constant as you type (no work around for this that I know of), and it won't be able to ctrl-click on it to jump to the class. The second issue is alleviated since you can quickly highlight "User" in the FQCN and then click ctrl-n (the default mapping for their "search for class" feature), and the resulting class search dialogue will be pre-loaded with the highlighted text

Related