Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ビューコンポーザーでコントローラをキレイにする

chiroruxx
January 26, 2019

 ビューコンポーザーでコントローラをキレイにする

2019/01/26 PHPカンファレンス仙台のLTで発表したスライドです。

chiroruxx

January 26, 2019
Tweet

More Decks by chiroruxx

Other Decks in Technology

Transcript

  1. 長くなりますよね・・・ public function show(Post $post) { $categories = Category::all(); foreach

    ($categories as $key => $category) { $category->count = Category::where('id', $category->id)->count(); $categories->put($key, $category); } $searchFormAttributes = [ 'type' => PostType::all()->pluck('value', 'id'), 'max' => 120, 'categories' => $categories->push(['name' => 'なし', 'id' => ''])->pluck('name', 'id'), ]; if (Auth::check()) { $user = Auth::user(); } else { $user = new User; } $relatedPosts = $post->relatedPosts; if ($relatedPosts->count() < 5) { $addPosts = Post::orderBy('id', 'desc')->take(5 - $relatedPosts->count())->get(); $relatedPosts = $relatedPosts->merge($addPosts); } return view( 'posts.show’, compact('posts', 'categories', 'searchFormAttributes', 'user', 'relatedPost’) ); }
  2. public function show(Post $post) { $categories = Category::all(); foreach ($categories

    as $key => $category) { $category->count = Category::where('id', $category->id)->count(); $categories->put($key, $category); } $searchFormAttributes = [ 'type' => PostType::all()->pluck('value', 'id'), 'max' => 120, 'categories' => $categories->push(['name' => 'なし', 'id' => ''])->pluck('name', 'id'), ]; if (Auth::check()) { $user = Auth::user(); } else { $user = new User; } $relatedPosts = $post->relatedPosts; if ($relatedPosts->count() < 5) { $addPosts = Post::orderBy('id', 'desc')->take(5 - $relatedPosts->count())->get(); $relatedPosts = $relatedPosts->merge($addPosts); } return view( 'posts.show’, compact('posts', 'categories', 'searchFormAttributes', 'user', 'relatedPost’) ); } 長くなりますよね・・・ カテゴリー一覧 検索フォーム ログイン関係 関連記事
  3. ビューコンポーザーを使った結果 ▪ コンポーザー(検索フォーム) public function compose(View $view) { $attributes =

    [ 'type' => PostType::all()->pluck('value', 'id'), 'max' => 120, 'categories' => Category::all()-> //... ]; $view->with('attributes', $attributes); }