Browse Source

Lesson 21: view composers.

Frederic G. MARAND 6 years ago
parent
commit
c2f851c43a
3 changed files with 20 additions and 13 deletions
  1. 1 12
      app/Http/Controllers/PostsController.php
  2. 15 0
      app/Post.php
  3. 4 1
      app/Providers/AppServiceProvider.php

+ 1 - 12
app/Http/Controllers/PostsController.php

@@ -60,18 +60,7 @@ class PostsController extends Controller
             ->filter($request->only(['month', 'year']))
             ->get();
 
-        // Temporarily here: will be moved when discussing view composers.
-        $archives = Post::selectRaw(<<<EOT
-year(created_at) as year,
-monthname(created_at) as month,
-count(*) published
-EOT
-        )->groupBy('year', 'month')
-            ->orderByRaw('min(created_at) desc')
-            ->get()
-            ->toArray();
-
-        return view('posts.index', compact('archives', 'posts'));
+        return view('posts.index', compact('archives'));
     }
 
     public function show(Post $post)

+ 15 - 0
app/Post.php

@@ -27,6 +27,21 @@ class Post extends Model
         $this->comments()->create(compact('body'));
     }
 
+    public static function archives()
+    {
+        $archives = static::selectRaw(<<<EOT
+year(created_at) as year,
+monthname(created_at) as month,
+count(*) published
+EOT
+        )->groupBy('year', 'month')
+            ->orderByRaw('min(created_at) desc')
+            ->get()
+            ->toArray();
+
+        return $archives;
+    }
+
     public function comments()
     {
         return $this->hasMany(Comment::class);

+ 4 - 1
app/Providers/AppServiceProvider.php

@@ -2,6 +2,7 @@
 
 namespace App\Providers;
 
+use App\Post;
 use Illuminate\Support\ServiceProvider;
 
 class AppServiceProvider extends ServiceProvider
@@ -13,7 +14,9 @@ class AppServiceProvider extends ServiceProvider
      */
     public function boot()
     {
-        //
+        view()->composer('layouts.sidebar', function ($view) {
+            $view->with('archives', Post::archives());
+        });
     }
 
     /**