Invokable > 戻る
2021-03-13
Laravel Blade View

Blade viewへのデータの渡し方いろいろ

  1. バージョン
  2. view()の第二引数
  3. view()->with()
  4. $view = view()
  5. ArrayAccess
  6. __set()
  7. withFoo()
  8. Bladeコンポーネント
  9. Livewire

バージョン

  • Laravel 8.x

The Laravel Framework. Contribute to laravel/framework development by creating an account on GitHub.

view()の第二引数

return view('welcome', ['name' => 'laravel']);

    /**
     * Get the evaluated view contents for the given view.
     *
     * @param  string|null  $view
     * @param  \Illuminate\Contracts\Support\Arrayable|array  $data
     * @param  array  $mergeData
     * @return \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory
     */
    function view($view = null, $data = [], $mergeData = [])

view()->with()

return view('welcome')->with(['name' => 'laravel']);

配列部分にcompact()を使うこの形が一番使う。

$name = 'laravel';

return view('welcome')->with(compact('name'));

with()はこれなのでwith(['key' => 'value'])でもwith('key', 'value')でもいい。

    /**
     * Add a piece of data to the view.
     *
     * @param  string|array  $key
     * @param  mixed  $value
     * @return $this
     */
    public function with($key, $value = null)
    {
        if (is_array($key)) {
            $this->data = array_merge($this->data, $key);
        } else {
            $this->data[$key] = $value;
        }

        return $this;
    }

複数のデータを渡すことを考えると最初から配列がいいけど->with('key', 'value')->with('key2', 'value2')と繋げてもいい。

$view = view()

$view = view('welcome');

$view->with('key', 'value');

return $view;

コントローラーの途中で渡すこともできるけど後から見た時に分かりにくいのであまり使わないほうがいい。

ArrayAccess

$view = view('welcome');

$view['key'] = 'value';

return $view;

__set()

$view = view('welcome');

$view->key = 'value';

return $view;

withFoo()

return view('welcome')->withKey('value');

使ったことないけどコードを見るとこの辺りも可能。

Bladeコンポーネント

publicプロパティは自動的にviewに渡されるのでrender()で渡さなくていい。

Livewire

Livewireでもpublicプロパティは自動的に渡される。
ただしLivewireではpublicプロパティで持ちたくないことも多いのでrender()で渡すこともある。

投稿者 Invokable
0件のコメントを読むにはログインしてください。
登録 ログイン