From 3a2ed286b6fa1b195475cc851725a77bef7a160b Mon Sep 17 00:00:00 2001 From: Amirmahdi Nourkazemi Date: Fri, 12 Jun 2026 15:25:12 +0330 Subject: [PATCH] feat: add paginatin to music --- app/Http/Controllers/MusicController.php | 26 +++++++++++++++--------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/app/Http/Controllers/MusicController.php b/app/Http/Controllers/MusicController.php index e8a06d8..e8f6fcd 100644 --- a/app/Http/Controllers/MusicController.php +++ b/app/Http/Controllers/MusicController.php @@ -32,23 +32,29 @@ public function getAllMusic() return response()->json($music); } - public function index() + public function index(Request $request) { $userId = auth()->id(); + // Paginated so clients don't pull the whole library at once. + $perPage = (int) $request->input('per_page', 20); + $perPage = max(1, min($perPage, 100)); + + // (public) OR (private AND owned by me) — grouped so it stays correct. $music = Music::with(['image', 'playlists']) - ->where('type', 'public') - ->orWhere(function($query) use ($userId) { - $query->where('type', 'private') - ->where('user_id', $userId); + ->where(function ($query) use ($userId) { + $query->where('type', 'public') + ->orWhere(function ($q) use ($userId) { + $q->where('type', 'private') + ->where('user_id', $userId); + }); }) ->orderBy('created_at', 'desc') - ->get(); + ->paginate($perPage); - return response()->json([ - 'data' => $music, - 'total' => $music->count() - ]); + // Laravel's paginator JSON keeps `data` and `total`, and adds + // current_page / last_page / per_page for the client. + return response()->json($music); } public function getMusicByPlaylist($playlistId)