Laravel How to return variables from php file to blade template

Viewed 1437

I have created a file localization.php and i defined some variable like:

localization.php

 <?php

 $color = 'red';
 $background = 'orange';

 ?>

now i included the localization.php file in all my blade templates like:

@include('localization') 

and here in template i want to echo the variables which i mentioned in localiztion.php

 {{$color}} //when i use this it show error 'undefined variable'

can you guys please help me to fix this

2 Answers

"i want to use this localization file in all view i have some genereic variables and i want to include this in all blade templates "

the best way to do this is put it on constants. in directory config>>constants.php

<?php 

return
[
'ToBeReturn' => [
     'color' => 'red',
     'background' => 'orange']
];

then at your controller you can return it

 public function index() 
    {
        return view('index')
                   ->with('color',config('constants.ToBeReturn.color')
                   ->with('background',config('constants.ToBeReturn.background'));
    }

now on your view you can view it as

{{ $color }}
{{ $background }}

do a

php artisan config:cache

This is the standard the MVC laravel follows. Putting variable in a view is not good. so since you want a localize variable, put it on constants.

I tried this and it works

View::share(with([
'color' => 'red',
'background' => 'orange'
]));

it works, but unfortunately it only allows to add in route file .

Related