---
# System prepended metadata

title: Laravel view composer
tags: [PHP, ' Backend', ' Laravel']

---

---
tags: PHP, Laravel, Backend
---

# Laravel view composer

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

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

## 創建Providers

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

```php=
<?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=
<?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);
        });
    }
}
```

### 附加到多個樣板中

加到`profile`及`dashboard`的樣板中

```php=
use App\Views\Composers\MultiComposer;
 
View::composer(
    ['profile', 'dashboard'],
    MultiComposer::class
);
```

加到所有樣板

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

## 新增服務

到`config/app.php`的`providers`數組中加入

`App\Providers\ViewServiceProvider::class`