Laravel 5:查看已加载的事件

时间:2015-05-06 16:39:34

标签: php events view laravel-5

我想听View加载(或渲染...)事件,我怎样才能使用*Event::文件中的routes.php外观在Laravel 5中执行此操作。

1 个答案:

答案 0 :(得分:1)

例如,如果您想在每次加载视图时传递一些常见数据,则可以使用view::composer,然后在这种情况下,在App \ Http \中创建view::composer ViewComposers'并使用如下服务提供商注册:

<?php namespace App\Providers;

use View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {

    public function boot()
    {
        // Run "compose" method from "App\Http\ViewComposers\ProfileComposer" class
        // whenever the "profile" view (Basically profile.blade.php) view is loaded
        View::composer('profile', 'App\Http\ViewComposers\ProfileComposer');
    }
}

然后像这样创建ProfileComposer(取自Laravel文档):

<?php namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;
use Illuminate\Users\Repository as UserRepository;

class ProfileComposer {

    protected $users;

    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }

    // Bind data to the view
    public function compose(View $view)
    {
        $view->with('count', $this->users->count());
    }
}

因此,每次加载profile view时,$count变量都将绑定在该视图中,您可以像view中的其他变量一样使用它。就是这样。详细了解Laravel website