Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Http\Controllers\Author;
- use DateTime;
- use DatePeriod;
- use DateInterval;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use App\Http\Controllers\Controller;
- class DashboardController extends Controller
- {
- public function index()
- {
- $count = [
- 'draft' => \App\Models\Post::where('author_id', auth()->user()->id)->where('status', 'draft')->count(),
- 'published' => \App\Models\Post::where('author_id', auth()->user()->id)->where('status', 'published')->count(),
- 'posts' => \App\Models\Post::where('author_id', auth()->user()->id)->count(),
- ];
- $posts = \App\Models\Post::selectRaw('count(*) as count, month(published_date) as month, year(published_date) as year')
- ->where('author_id', auth()->user()->id)
- ->where('published_date', '>=', DB::raw('DATE_SUB(CURDATE(), INTERVAL 12 MONTH)'))
- ->groupBy('year', 'month')
- ->orderBy('year')
- ->orderBy('month')
- ->get()
- ->toArray();
- $postCounts = [];
- foreach ($this->getLast12Months() as $date) {
- $month = $date['month'];
- $monthName = $date['month_name'];
- $year = $date['year'];
- $postCounts[] = [
- 'count' => collect($posts)->where('month', $month)->where('year', $year)->first()['count'] ?? 0,
- 'month' => $month,
- 'month_name' => $monthName,
- 'year' => $year,
- ];
- }
- return view('author.dashboard', compact('count', 'postCounts'));
- }
- function getLast12Months()
- {
- $months = [];
- $start = new DateTime;
- $start->setDate($start->format('Y'), $start->format('n'), 1); // Normalize the day to 1
- $start->setTime(0, 0, 0); // Normalize time to midnight
- $start->sub(new DateInterval('P12M'));
- $interval = new DateInterval('P1M');
- $recurrences = 12;
- foreach (new DatePeriod($start, $interval, $recurrences, true) as $date) {
- $months[] = [
- 'month' => $date->format('n'),
- 'month_name' => $date->format('F'),
- 'year' => $date->format('Y')
- ];
- }
- return $months;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment