Pregunta

Model: Comment.php

class Comment extends Eloquent {
    protected $table = 'comments';
    public $timestamps = true;
}

Controller: PageController.php

class PageController extends BaseController {
    $top_comments = Comment::take(3)->get();
    return View::make('page', array('top_comments' => $top_comments));
}

View: page.blade.php

@foreach ($top_comments as $comment)
    user #{{ $comment->user_id }}:<br />
    {{ $comment->comment}}
@endforeach

This works perfect with the page.blade.php view which I can define as a route (/page). However, I can't seem to figure out how to achieve this globally.

Example: I want to be able to use the @foreach containing $top_comments in my master.blade.php file. Right now if I was to use the above, it works great on /page but not on /, /about, /tos

¿Fue útil?

Solución

You can use View::share('top_comments', Comment::take(3)->get()); to make it available everywhere. Of course, you'll have to place it some place where it gets loaded no matter what page you load if you want it in every possible view. (One such place would be in the __construct() method of your BaseController, but I doubt that could be considered a best practice. Not sure where I'd put it myself.)

Another way would be to leverage view composers, like this:

View::composer('master', function($view)
{
    $view->with('top_comments', Comment::take(3)->get());
});

This works if you meant that you want it in your master.blade.php no matter from where it is loaded, because it's bound to that view. If you choose this option, I recommend for instance creating a file composers.php and including that in app/start/global.php.

That said, I assume your controller sample above left something out, because it looks like it's missing a method declaration.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top