Use variables external to Route do Laravel 5 to send to view

Asked

Viewed 198 times

0

Hi, I’m working with Laravel, and in my Routes file, I would like to leave created a variable that I want to use in 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...) the Laravel cannot find the variable $foo, even if it is declared before the route structures and in the configuration file itself.

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

Errorexception (E_NOTICE). Undefined variable: foo

How to solve?

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

1 answer

2


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

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

This way, the variable will be accessed for reading only

If you need to change the external 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]); 
});
  • 1

    excellent, thank you very much!!! turned out that I preferred to leave inside the file .env even so I can use this static statement in other system locations, but thank you so much anyway...

  • 1

    yes, I would recommend that very @Leandroluk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.