F
F
FREDF2015-04-27 13:47:57
Laravel
FREDF, 2015-04-27 13:47:57

How to pass variable from Controller to View in Laravel?

Hello!
Using Composer installed the latest version of Laravel.
I ran into a banal problem ..
I want to transfer a variable to the View, but nothing happens.
In Controller ( HomeController.php ) specified the following:

public function showWelcome(){
  $data['cheese'] = 'My pretty variable';
  return View::make('hello', $data);
}

In View ( hello.blade.php ):
{{ $data['cheese'] }}
{{ $cheese }}
{{ cheese }}
<? echo $cheese; ?>
<? echo $data['cheese']; ?>

None of these constructs work. debug response: Undefined variable
Tell me what I'm doing wrong? If anyone is not too lazy, explain briefly how MVC works in Laravel in general.
PS: Problem solved. In the app/routes.php file, View output was specified immediately (bypassing the controller)
Solution:
/*
Route::get('/', function()
{
  return View::make('hello');
});
*/

Route::get('/', '[email protected]');

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
JhaoDa, 2015-04-27
@FREDF

In general, you have some kind of anomaly there.
Works great:

public function showWelcome(){
    $data['cheese'] = 'My pretty variable';
    return View::make('hello', $data);

    // or
    return View::make('hello', ['cheese' => 'My pretty variable']);

    // or
    $cheese = 'My pretty variable';
    return View::make('hello', compact('cheese'));
}

{{ $cheese }}

F
FREDF, 2015-04-27
@FREDF

These solutions don't work.
35fa6a01f84b473093770015098abed1.png

M
Max, 2015-04-27
@AloneCoder

Well, in theory, {{ $cheese }} is needed

M
Mokhirjon Naimov, 2015-04-27
@zvermafia

controller:

public function showWelcome()
{
    $data['cheese'] = 'My pretty variable';

    return View::make('hello', array(
        'data' => $data,
    );
}

View:
Or you can use compact():
public function showWelcome()
{
    $data['cheese'] = 'My pretty variable';

    return View::make('hello')->compact('data');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question