dongshi6969
2018-06-14 12:32
浏览 137
已采纳

使用Laravel 5.6在包含的视图中传递数据

Using Laravel 5.6, I'm trying to get the number of received links a logged-in user may have in my application.

public function getReceivedLinksCount() {
    return $count = App\Link::where([
                ['recipient_id', Auth::id()],
                ['sender_id', '!=', Auth::id()]
            ])->count();
}

So far, so good. Question is not about that piece of code, but where I can use it. I'd like to display this counter on the navigation bar of the website (Facebook's style) which is in my header.blade.php which is included in every page.

I'd like to do it with a clean code, of course. It seems like I need to use View Composers but I'm not sure it's the right way to do it, and not sure on how the code is supposed to look.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanpa5237 2018-06-14 18:48
    已采纳
    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\ServiceProvider;
    
    class AppServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            view()->composer('layouts.header', function ($view) {
                $view->with('variable_name', \App\Path-To-Your-Model::something());
            });
        }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douniwan_0025 2018-06-14 13:23

    You can share a value across all views by using View::share(), see docs

    For example

    class AppServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            $linksCount = Link::getReceivedLinksCount();
            View::share('linksCount', $linksCount);
        }
    
        ...
    
    }
    

    This works well if you want to set the value everywhere. Personally, I would set the value in the constructor of a 'BaseController' that gets extended by other controllers. This makes the code more discoverable because most people would expect view values to be set in a controller. And it's also a bit more flexible if you plan on having a section of your app that doesn't require that value to be computed.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题