Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to access class constants from a blade template

Tags:

laravel

blade

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.

like image 211
DatsunBing Avatar asked Nov 12 '17 21:11

DatsunBing


People also ask

How do you check variables in blade?

If you want to check if the variable exists, use isset otherwise use empty if the variable will always be set and you want to determine if its value is falsey.

What is the advantage of Laravel blade template?

The blade templates are stored in the /resources/view directory. The main advantage of using the blade template is that we can create the master template, which can be extended by other files.

What is @stack in Laravel blade?

One of blade directive @stack('scripts') is very helpful when you have javascript need to execute in the child page. I create a fresh Laravel installation to demo an example. I have to make auth scaffolding with laravel/ui package because I'm using Laravel 6.


1 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

like image 99
Daniel L Avatar answered Oct 10 '22 22:10

Daniel L