0
1

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 3 years have passed since last update.

【Laravel】Bladeで共通で参照できるグローバルな変数を定義する。

Posted at

自分用のメモとして残します。

各コントローラでわざわざviewに渡す変数を定義するのは面倒。
AppServiceProviderのbootメソッドで、全てのviewで参照できる変数をに定義する方法をメモ。

やり方

app\Providers\AppServiceProvider.php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;


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

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // view()->composer内でやっているのは、Authの情報を取るためなので、なくてもOK
        view()->composer('*', function ($view)
        {
            $globalArg_hoge = null;
            if (Auth::guard('user')->check()) {
                $globalArg_hoge = 'HOGE';
            }


            // ポイント:view()->shareで変数を定義してあげることで、冗長にならなくなる。
            view()->share([
                'globalArg_hoge'=> $globalArg_hoge,
            ]);

        });

    }
}

以上です。

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?