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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With