File: /var/www/html/sarvodayahospital/app/Http/Controllers/NewsController.php
<?php
namespace App\Http\Controllers;
use App\Models\CMSPage;
use App\Models\News;
use Artesaos\SEOTools\Facades\OpenGraph;
use Artesaos\SEOTools\Facades\SEOMeta;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class NewsController extends Controller
{
public function index(Request $request)
{
$sort_by = $request->filled('sortby') ? $request->get('sortby') : 'id';
$by_year = $request->filled('year') ? (int) $request->get('year') : 0;
$by_month = $request->filled('month') ? (int) $request->get('month') : null;
$seo = [];
$query = News::query()->has('newsTypeCollection');
$query->when(
$by_year > 0,
function ($q) use ($by_year) {
return $q->whereYear('PublicationDate', $by_year);
}
);
if ($by_year == 0) {
$query->when(
$by_month > 0,
function ($q) use ($by_month) {
return $q->whereMonth('PublicationDate', $by_month)
->whereYear('PublicationDate', date("Y"));
}
);
} else {
$query->when(
$by_month > 0,
function ($q) use ($by_month) {
return $q->whereMonth('PublicationDate', $by_month);
}
);
}
// $query->when(
// $sort_by == 'A-Z', function ($q) {
// return $q->orderBy('Title', 'ASC');
// }
// );
// $query->when(
// $sort_by == 'Latest', function ($q) {
// return $q->orderBy('published_at', 'DESC');
// }
// );
// $query->when(
// $sort_by == 'Z-A', function ($q) {
// return $q->orderBy('Title', 'DESC');
// }
// );
$news = $query->orderBy('PublicationDate', 'DESC')->paginate(60)->appends(request()->query());
$years = News::query()
->select(DB::raw('YEAR(PublicationDate) as publicationYear'))
->groupBy('publicationYear')
->orderBy('publicationYear', 'DESC')
->get();
$cmsPage = CMSPage::query()
->where('Slug', request()->path())
->firstOrFail();
if ($cmsPage) {
$seo = $cmsPage->seoComponent()->first();
}
return view('pages.news', compact('news', 'years', 'seo'));
}
}