Laravel view composer

在某些情況下須傳遞參數底層樣板,例如想要將網頁瀏覽人數放在layouts.app,就需要使用view composer

可以使用 class 的方式傳入,或是閉包

創建 Providers

可以在App\View\Composers創建一個ProfileComposer檔案

<?php
namespace App\View\Composers;

class ProfileComposer
{
public function compose($view)
{
$view->with('viewCount', 100);
}
}

然後創建一個Providers檔案,利用class或是閉包方式傳入,View::composer第一個參數為blade位置名稱

指令: php artisan make:provider ViewServiceProvider

<?php

namespace App\Providers;

use App\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Using class based composers...
View::composer('profile', ProfileComposer::class);

// Using closure based composers...
View::composer('profile', function ($view) {
$view->with('viewCount', 100);
});
}
}

附加到多個樣板中

加到profiledashboard的樣板中

use App\Views\Composers\MultiComposer;

View::composer(
['profile', 'dashboard'],
MultiComposer::class
);

加到所有樣板

View::composer('*', function ($view) {
//
});

新增服務

config/app.phpproviders數組中加入

App\Providers\ViewServiceProvider::class