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

使用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());
            });
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?