Tomek Buszewski
Tomek Buszewski

Reputation: 7955

Passing ArrayAccess from Controller to View in Laravel 4

I try to learn Laravel 4 and I have found it - so far - pretty great. But Blade templaes seem dfficult to me, less intuitive than Smarty for instance.

I have a small problem. I try to push my data from Controller to a View. I do this:

public function getGame($id, $slug = null) {
    $game['info'] = Game::find($id);
    $game['genres'] = Game::find($id)->genres()->get();
    $game['dev'] = Game::find($id)->developers()->get();

    $this->layout = View::make('user')->with('game',$game);
}

Pretty straightforward, isn't it? For now, my View is just {{ $game['info']->title }}. But it seems that it doesn't see my variable (throwing "Undefined variable: game"). What can I do? Can I post the data in that array format (I assumed from the docs that I can).

Upvotes: 1

Views: 1638

Answers (1)

vlad
vlad

Reputation: 626

I think the problem is in the last line of your code. You either return a view like

return View::make('user')->with('game', $game);

or do something like this:

Create protected $layout = 'my_layout.blade.php' in your controller and create the file my_layout.blade.php and put it into views folder. In it write something like

@yield('content')

Then, create your user.blade.php and create a section like this

@section('content')
    ....
@stop

Finaly, at the end of your getGame function

$this->layout->content = View::make('user')->with('game', $game);

Home this make sense to you.

Btw, why not define 'genres' and 'developers' relationships in your Game model and then use eager loading like

$game = Game::with('genres', 'developers')->find( $id );

and pass this to the view. Then access title like $game->title, genres like $game->genres->... etc.

Regards, Vlad

Upvotes: 1

Related Questions