做法
以 User
模型為例,在 app\Http\ViewComposers\
資料夾新增一個 UserComposer.php
檔:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| namespace App\Http\ViewComposers;
use App\User; use Illuminate\View\View;
class UserComposer {
protected $user;
public function __construct(User $user) { $this->user = $user; }
public function compose(View $view) { $view->with('count', $this->user->count()); } }
|
在 app\Providers
資料夾新增一個 app\Providers\ComposerServiceProvider.php
服務提供者:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| namespace App\Providers;
use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider {
public function boot() { View::composer( ['layouts.app'], \App\Http\ViewComposers\UserComposer::class ); }
public function register() { } }
|
在 composer()
方法的第 1 個參數,可以使用「*
」萬用字元將資料傳遞給所有視圖。
1 2 3
| View::composer( '*', \App\Http\ViewComposers\UserComposer::class );
|
將服務提供者註冊到 config\app.php
檔:
1 2 3 4 5 6 7 8 9 10
| return [
'providers' => [
\\ ... App\Providers\ComposerServiceProvider::class,
],
];
|
在視圖中使用變數:
參考資料