0

I tried to pass a variable from Controller to View in Laravel with a simple variable, but It caused an error: Underfined variable.

I tried to change:

return view('home', $Test);

or

return view('home', 'Test' => $Test);

or

return view('home')->with('Test');

My Controller:

        public function index(){
           $Test = 55;
           return view('home',compact('Test'));
          }

My view

            <html>
             <body>
              <h1> {{$Test}} </h1>
             </body>
            </html>

This is error:

ErrorException {#229 ▼
  #message: "Undefined variable: Test"
  #code: 0
  #file: "E:\Desktop\aroundtrips\storage\framework\views\245291ca31ad79efeff6d548bc38081345e95242.php"
  #line: 78
  #severity: E_NOTICE
}
Hàm Louis
  • 41
  • 7
  • 1
    There might already be an answer here: https://stackoverflow.com/questions/18341792/how-to-pass-data-to-view-in-laravel/37559664 – SScotti Jun 28 '19 at 00:30

4 Answers4

1

Pass it like below

return view('home', ['Test' => $Test]);

For reference check https://laravel.com/docs/5.8/views

prabhat
  • 620
  • 5
  • 18
  • Thanks guy, I don't know why, but the only solution that I install laravel project with specific 5.7 version is best solution, I think 5.8 version has changed something – Hàm Louis Jun 28 '19 at 04:51
0

Just using compact('Test') is going to pass your variable to the view.

So if you leave your controller and view as shown in your question it's going to work.

0
return view('home')->with('Test', $test);
0

I initially had same problem with Laravel 5.7 where the with() method must be used to pass the variable to the blade template. But I have tested your original code on my own Laravel 5.8 setup and it works flawlessly:

public function index()
{
    $Test = 55;
    return view('home', compact('Test'));
}
Udo E.
  • 2,665
  • 2
  • 21
  • 33
  • It still has a error like this: ErrorException {#227 ▼ #message: "Undefined variable: Test" #code: 0 #file: "E:\Desktop\aroundtrips\storage\framework\views\245291ca31ad79efeff6d548bc38081345e95242.php" #line: 78 #severity: E_NOTICE } 1 – Hàm Louis Jun 29 '19 at 17:10
  • if you upgraded to Laravel 5.8 from a previous version, make sure you run `vagrant provision` in homestead directory and retest your site. Also, ensure `composer.json` is the latest version. – Udo E. Jun 29 '19 at 18:37