Last active
May 21, 2025 14:50
-
-
Save ShaneRich5/239ac923a9bf7422d4b55f63cb24da12 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function index(Request $request) | |
{ | |
$query = Post::query(); | |
$query->where('status', $request->input('status')); | |
$query->whereHas('author', function ($q) use ($request) { | |
$q->where('name', 'like', '%' . $request->input('author') . '%'); | |
}); | |
// Optional filters | |
if ($request->filled('published_before')) { | |
$query->where('published_at', '<=', $request->date('published_before')); | |
} | |
if ($request->filled('published_after')) { | |
$query->where('published_at', '>=', $request->date('published_after')); | |
} | |
// Optional boolean flag | |
if ($request->boolean('with_comments')) { | |
$query->with('comments.author'); | |
} | |
$query->orderBy('published_at', 'desc'); | |
// Complex pagination condition | |
$perPage = $request->integer('per_page', 10); | |
$posts = $query->paginate($perPage)->appends($request->all()); | |
return response()->json([ | |
'filters' => $request->only(['status', 'author', 'published_before', 'published_after']), | |
'meta' => [ | |
'total' => $posts->total(), | |
'per_page' => $posts->perPage(), | |
], | |
'data' => $posts->items(), | |
]); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function store(Request $request) | |
{ | |
$data = $request->validate([ | |
'title' => 'required|string|max:255', | |
'body' => 'required|string', | |
]); | |
if (strlen($data['body']) < 50) { | |
return response()->json(['error' => 'Post body must be at least 50 characters.'], 422); | |
} | |
$post = Post::create([ | |
'user_id' => auth()->id(), | |
'title' => $data['title'], | |
'body' => $data['body'], | |
'published' => false, | |
]); | |
return response()->json($post, 201); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment