在Laravel的layout.app.blade中显示计数器变量

时间:2019-03-24 10:13:50

标签: laravel

我想在我的app.blade中显示计数器,该计数器在所有页面中都被调用,如下面的屏幕截图

enter image description here

我的控制器中只有此功能

class ReportsController extends Controller
{
    public function invoiceTransaction()
    {   
        $salespayments = Salespayments::where('type','=','check')->get();
        $countUnread = Salespayments::select(DB::raw("SUM(unread) as unread"))->get();


        return view('reports.invoiceTransactions')
                        ->with('salespayments', $salespayments)
                        ->with('countUnread', $countUnread);
    }
}

我正在通过此{{$countUnread[0]->unread}}

在刀片服务器上呼叫计数器

如何使该函数在app.blade.php中可读?非常感谢!

2 个答案:

答案 0 :(得分:2)

AppServiceProvider中,您可以使用sum在所有视图中共享view()->share();

赞:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot() {
   $countUnread = Salespayments::sum('unread');
   view()->share('countUnread', $countUnread);
}

答案 1 :(得分:0)

首先成为服务提供商,

php artisan make:provider CounterServiceProvider

然后在您的CounterServiceProvider文件中。

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Views\Composers;

class CounterServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // here define your master layout
        $this->app['view']->composer(['master'], Composers\Counter::class);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

现在在您的App\Views\Composers文件夹中添加Counter类。

<?php
namespace App\Views\Composers;

use Illuminate\View\View;

class Counter {

    public function compose(View $view)
    {
        $view->with('countUnread', session('countUnread'));
    }
}

确保将CounterServiceProvider添加到config / app.php文件的providers数组中。