Use external variables to route from Laravel 5 to send to view

0
Hello, I'm working with Laravel , and in my Routes file, I'd like to leave a variable I want to use on all routes, like this:

/routes/web.php

$foo = "ola mundo";

Route::get('/', function () {
    return view('page1', ["title" => "teste - $foo"]); //concatenação direta
});
Route::get('/page2', function () {
    return view('page2', ["title" => "bar - ".$foo]);  //concatenação por mesclagem
});

My problem is that (which makes no sense ...) Laravel is not able to find the $foo variable, even if it is declared before the route structures and in the configuration file itself. >

Regardless of the type of concatenation I use, Laravel does not understand and gives me the error:

  

ErrorException (E_NOTICE). Undefined variable: foo

How to solve?

EDIT: I made a test defining a custom variable inside the file .env and calling it through the env('CUSTOM_FOO') method that Laravel makes available and I had no problem, but in a variable created in the file itself (and that in my understanding of PHP should have been found) does not work ...

    
asked by anonymous 03.10.2017 / 14:37

1 answer

2

Variables external to an anonymous function are not visible inside them, so you can use this variable inside an anonymous function you need to use use() after calling the function, see:

$foo = 'foo';
Route::get('/', function () use ($foo) {
    return view('page1', ["title" => "bar - ".$foo]);
});
  

In this way, the variable will be read-only

If you need to change the foreign variable to an anonymous function, you need to pass it by reference:

$foo = 'foo';
Route::get('/', function () use (&$foo) {
    return view('page1', ["title" => "bar - ".$foo]); 
});
    
03.10.2017 / 14:55