在 Laravel 7.0 使用 View Composer 視圖合成器

做法

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
{
/**
* The user model.
*
* @var User
*/
protected $user;

/**
* Create a new user composer.
*
* @param User $user
* @return void
*/
public function __construct(User $user)
{
$this->user = $user;
}

/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
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
{
/**
* Register bindings in the container.
*
* @return void
*/
public function boot()
{
View::composer(
['layouts.app'],
\App\Http\ViewComposers\UserComposer::class
);
}

/**
* Register the service provider.
*
* @return void
*/
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,

],

];

在視圖中使用變數:

1
<div>{{ count }}</div>

參考資料