Skip to content

Commit 7a17704

Browse files
feat(PublicController): refactor articles method to use validated request data for improved query handling
1 parent 3e90ec6 commit 7a17704

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

app/Http/Controllers/General/PublicController.php

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,22 +48,29 @@ public function about()
4848
*/
4949
public function articles(Request $request)
5050
{
51-
$category = trim($request->query('category'));
52-
$search = trim($request->query('search'));
53-
$start_date = trim($request->query('start_date_creation'));
54-
$end_date = trim($request->query('end_date_creation'));
51+
$validated = $request->validate([
52+
'category' => ['sometimes', 'nullable', 'string'],
53+
'search' => ['sometimes', 'nullable', 'string'],
54+
'start_date_creation' => ['sometimes', 'nullable', 'date'],
55+
'end_date_creation' => ['sometimes', 'nullable', 'date'],
56+
]);
57+
58+
$category = trim($validated['category'] ?? '');
59+
$search = trim($validated['search'] ?? '');
60+
$start_date = trim($validated['start_date_creation'] ?? '');
61+
$end_date = trim($validated['end_date_creation'] ?? '');
5562

5663
$isSql = $this->isSqlDriver;
5764

5865
$articles = Article::whereIsPublished(true)
5966
->with(['user' => fn ($query) => $query->select('id', 'name', 'avatar')])
6067
->with(['categories' => fn ($query) => $query->select('id', 'name')])
61-
->when($request->filled('category'), function ($query) use ($category) {
68+
->when($category, function ($query) use ($category) {
6269
$names = array_filter(array_map('trim', explode(',', $category)));
6370

6471
return $query->whereHas('categories', fn ($q) => $q->whereIn('name', $names));
6572
})
66-
->when($request->filled('search'), fn ($q) => $q->where(function ($query) use ($search, $isSql) {
73+
->when($search, fn ($q) => $q->where(function ($query) use ($search, $isSql) {
6774
if ($isSql) {
6875
$booleanQuery = Helpers::buildBooleanQuery($search);
6976
$query->whereFullText(['title', 'subtitle', 'excerpt', 'content_html'], $booleanQuery, ['mode' => 'boolean']);
@@ -72,8 +79,8 @@ public function articles(Request $request)
7279
->orWhereLike('excerpt', "%$search%")->orWhereLike('content_html', "%$search%");
7380
}
7481
})->orWhereHas('user', fn ($q) => $q->whereLike('name', "%$search%")))
75-
->when($request->filled('start_date_creation'), fn ($query) => $query->whereDate('created_at', '>=', $start_date))
76-
->when($request->filled('end_date_creation'), fn ($query) => $query->whereDate('created_at', '<=', $end_date))
82+
->when($start_date, fn ($query) => $query->whereDate('created_at', '>=', $start_date))
83+
->when($end_date, fn ($query) => $query->whereDate('created_at', '<=', $end_date))
7784
->latest()
7885
->paginate(10, ['id', 'user_id', 'title', 'slug', 'excerpt', 'thumbnail', 'created_at'])
7986
->withQueryString();

0 commit comments

Comments
 (0)