I have a problem in global variables in laravel. I know about view composer and my question is not related to that subject. How can I do such a simple thing in laravel view (*.blade.php | .php) template engine? for example this is a sample code from one of my views (.blade.php | *.php):
<?php
function myFunc() {
global $myvar;
if ( ! $myvar ) {
$myvar = 'my var is empty';
}
dd( $myvar );
}
$myvar = 'my var value';
myFunc();
At the end of the execution it shows up 'my var is empty' and not 'my var value'. Anybody knows why this happens?
In Laravel you can pass values from your included sub-blade to your main blade by declaring the variable you wish to pass values with as global in both the main and sub view. The key is declaring the passing variable as global on both ends (i.e., in both the main and included blade).
For instance:
INCLUDED SUB-BLADE
MAIN BLADE:
Hope this helps.
The best solution is to use the
Config
facade. You can create a new config file and set, in your case, global variables statically. But the best feature of this facade, are theget()
andset()
methods, which allow you to define these variables dynamically. See: Set Global variables in Laravel 5In your case:
Make sure you import the
Config
facade by usinguse
on the top of your file.Finally I found my answer, it has scope issue. because laravel uses class and methods to retrieve view so based on this page inforamtion: http://php.net/manual/en/language.variables.scope.php#98811
so we can write the code like this: