LoginSignup
23
19

More than 5 years have passed since last update.

Laravel ViewComposer を使ってみよう

Posted at

// Home
Route::get('home', function() {
    $posts = Post::recent();
    return view('home', compact('posts'))
});

// このサイトについて
Route::get('about', function() {
    $posts = Post::recent();
    return view('home', compact('posts'))
});

こんなコードを書いていませんか?
全ページサイドバーに表示するような情報を各route(もしくはController)で取得している点が気になります。

全ページで使う値はViewComposerでまとめて記述してしまいましょう。

(抜粋)SomeServiceProvider.php
public function boot()
{
    view()->share('posts', Post::recent());
}

もし単一 or 特定のViewでしかつかわない場合はこのように記述することもできます。

次の例は、サイドバー('common/sidebar.blade.php')が読み込まれた場合に posts を view に渡します。

(抜粋)SomeServiceProvider.php
public function boot()
{
    view()->composer('common.sidebar', function($view) {
        $view->with('posts', Post::recent());
    }
}

サイドバー(common/sidebar.blade.php)に加えて、フッター(common/footer.blade.php)にも渡したい場合は配列で指定することができます。

(抜粋)SomeServiceProvider.php
public function boot()
{
    view()->composer(['common.sidebar', 'common.footer'], function($view) {
        $view->with('posts', Post::recent());
    }
}

ここまで、ServiceProvider に直接記述する方法を紹介してきましたが、これも数が多くなってくると煩雑になってきます。クラス化してみましょう。

app/Http/ViewComposers/RecentPostsComposer.php
<?php

namespace App\Http\ViewComposers;

use App\Post;
use Illuminate\Contacts\View\View

class RecentPostComposer
{
    public function compose(View $view)
    {
        $view->with('posts', Post::recent());
    }
}
(抜粋)AppServiceProvider.php
public function boot()
{
    view()->composer(
        'common.sidebar',
        App\Http\ViewComposers\RecentPostComposer::class
    )
}
23
19
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
23
19