15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelでViewに共通の変数をmiddlewareで設定する

Last updated at Posted at 2019-09-20

概要

ログインユーザーの情報などサイト全体で常に使うデータがあると思います。常に必要なデータmiddlewareでViewに渡しておくことで処理を共通化出来ます。

手順

  1. middlewareを作成
  2. middlewareを登録

middlewareを作成

middlewareを新規作成します。

php artisan make:middleware SetUser

ViewFactoryに変数を渡しておくと、デフォルトの値として入ります。

app\Http\Middleware\SetUser.php
<?php

namespace App\Http\Middleware;

use Illuminate\Auth\AuthManager;
use Illuminate\View\Factory;

class SetUser
{
    public function __construct(Factory $viewFactory, AuthManager $authManager)
    {
        $this->viewFactory = $viewFactory;
        $this->authManager = $authManager;
    }

    public function handle($request, \Closure $next)
    {
        $user = $this->authManager->user();
        $this->viewFactory->share('user', $user);

        return $next($request);
    }
}

middlewareの登録

Kernel.phpにmiddlewareを登録します。

app\Http\Kernel.php
<?php

class Kernel extends HttpKernel {

    ......

    protected $routeMiddleware = [
        ......
        'setUser' => \App\Http\Middleware\SetUser::class,
    ];

}


15
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?