martinms

Untitled

Jun 5th, 2023
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.32 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Http\Controllers\Author;
  4.  
  5. use DateTime;
  6. use DatePeriod;
  7. use DateInterval;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\DB;
  10. use App\Http\Controllers\Controller;
  11.  
  12. class DashboardController extends Controller
  13. {
  14.     public function index()
  15.     {
  16.         $count = [
  17.             'draft' => \App\Models\Post::where('author_id', auth()->user()->id)->where('status', 'draft')->count(),
  18.             'published' => \App\Models\Post::where('author_id', auth()->user()->id)->where('status', 'published')->count(),
  19.             'posts' => \App\Models\Post::where('author_id', auth()->user()->id)->count(),
  20.         ];
  21.  
  22.         $posts = \App\Models\Post::selectRaw('count(*) as count, month(published_date) as month, year(published_date) as year')
  23.             ->where('author_id', auth()->user()->id)
  24.             ->where('published_date', '>=', DB::raw('DATE_SUB(CURDATE(), INTERVAL 12 MONTH)'))
  25.             ->groupBy('year', 'month')
  26.             ->orderBy('year')
  27.             ->orderBy('month')
  28.             ->get()
  29.             ->toArray();
  30.  
  31.         $postCounts = [];
  32.  
  33.         foreach ($this->getLast12Months() as $date) {
  34.             $month = $date['month'];
  35.             $monthName = $date['month_name'];
  36.             $year = $date['year'];
  37.  
  38.             $postCounts[] = [
  39.                 'count' => collect($posts)->where('month', $month)->where('year', $year)->first()['count'] ?? 0,
  40.                 'month' => $month,
  41.                 'month_name' => $monthName,
  42.                 'year' => $year,
  43.             ];
  44.         }
  45.  
  46.         return view('author.dashboard', compact('count', 'postCounts'));
  47.     }
  48.  
  49.     function getLast12Months()
  50.     {
  51.         $months = [];
  52.  
  53.         $start = new DateTime;
  54.         $start->setDate($start->format('Y'), $start->format('n'), 1); // Normalize the day to 1
  55.         $start->setTime(0, 0, 0); // Normalize time to midnight
  56.         $start->sub(new DateInterval('P12M'));
  57.         $interval = new DateInterval('P1M');
  58.         $recurrences = 12;
  59.  
  60.         foreach (new DatePeriod($start, $interval, $recurrences, true) as $date) {
  61.             $months[] = [
  62.                 'month' => $date->format('n'),
  63.                 'month_name' => $date->format('F'),
  64.                 'year' => $date->format('Y')
  65.             ];
  66.         }
  67.  
  68.         return $months;
  69.     }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment