Author SHA1 Message Date
Amirmahdi d0d48866f0 feat: user rating and comment 2026-05-20 15:52:28 +03:30
Amirmahdi 02448db346 refactor 2026-05-20 15:42:10 +03:30
Amirmahdi 6f5224a5d9 feat: add rating and comement 2026-05-20 12:19:10 +03:30
Amirmahdi e446de79fd fix: music test apis 2026-05-20 08:48:35 +03:30
Amirmahdi 65db1bd5da feat: add music feature 2026-05-19 08:22:10 +03:30
24 changed files with 1395 additions and 125 deletions
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CommentController extends Controller
{
/**
* Add comment to any model
*/
public function addComment(Request $request, $type, $id)
{
$request->validate([
'content' => 'required|string|max:1000',
]);
$model = $this->getModel($type, $id);
$this->checkAccess($model);
$comment = $model->comments()->create([
'user_id' => auth()->id(),
'content' => $request->content,
]);
return response()->json([
'message' => 'Comment added successfully',
'comment' => $comment->load('user'),
], 201);
}
/**
* Get all comments for a model
*/
public function getComments($type, $id)
{
$model = $this->getModel($type, $id);
$this->checkAccess($model);
$comments = $model->comments()
->with('user')
->latest()
->paginate(20);
return response()->json($comments);
}
/**
* Update comment
*/
public function updateComment(Request $request, $type, $id, $commentId)
{
$request->validate([
'content' => 'required|string|max:1000',
]);
$comment = Comment::where('id', $commentId)
->where('user_id', auth()->id())
->where('commentable_id', $id)
->where('commentable_type', $this->getModelClass($type))
->firstOrFail();
$comment->update([
'content' => $request->content,
]);
return response()->json([
'message' => 'Comment updated successfully',
'comment' => $comment->load('user'),
]);
}
/**
* Delete comment
*/
public function deleteComment($type, $id, $commentId)
{
$comment = Comment::where('id', $commentId)
->where('user_id', auth()->id())
->where('commentable_id', $id)
->where('commentable_type', $this->getModelClass($type))
->firstOrFail();
$comment->delete();
return response()->json([
'message' => 'Comment deleted successfully',
]);
}
/**
* Get most commented items
*/
public function mostCommented($type)
{
$modelClass = $this->getModelClass($type);
$userId = auth()->id();
$items = $modelClass::with(['image', 'user'])
->withCount('comments')
->where(function($query) use ($modelClass, $userId) {
if (property_exists($modelClass, 'type')) {
$query->where('type', 'public')
->orWhere(function($q) use ($userId) {
$q->where('type', 'private')
->where('user_id', $userId);
});
}
})
->orderBy('comments_count', 'desc')
->limit(10)
->get();
return response()->json($items);
}
private function getModel($type, $id)
{
$modelClass = $this->getModelClass($type);
$model = $modelClass::findOrFail($id);
return $model;
}
private function getModelClass($type)
{
$models = [
'music' => \App\Models\Music::class,
'media' => \App\Models\Media::class,
];
if (!isset($models[$type])) {
abort(404, 'Invalid model type');
}
return $models[$type];
}
private function checkAccess($model)
{
if (property_exists($model, 'type') && $model->type === 'private') {
if (auth()->id() !== $model->user_id) {
abort(403, 'You do not have access to this item');
}
}
}
}
+33 -5
View File
@@ -321,7 +321,16 @@ public function filters(Request $request)
public function show($id) public function show($id)
{ {
$media = Media::with(['image', 'category', 'myNote', 'tags' ,'comments']) $media = Media::with([
'image',
'category',
'myNote',
'tags',
'comments' => function($query) {
$query->with('user')->latest()->limit(10);
},
'ratings'
])
->where('id', $id) ->where('id', $id)
->where(function($query) { ->where(function($query) {
$query->where('visibility', 'public') $query->where('visibility', 'public')
@@ -329,6 +338,15 @@ public function show($id)
}) })
->firstOrFail(); ->firstOrFail();
// Get user's specific comment
$userComment = $media->userComment();
// Get paginated comments
$comments = $media->comments()
->with('user')
->latest()
->paginate(15);
return response()->json([ return response()->json([
'id' => $media->id, 'id' => $media->id,
'title' => $media->title, 'title' => $media->title,
@@ -340,16 +358,26 @@ public function show($id)
'visibility' => $media->visibility, 'visibility' => $media->visibility,
'created_at' => $media->created_at, 'created_at' => $media->created_at,
'updated_at' => $media->updated_at, 'updated_at' => $media->updated_at,
'is_premium' => $media->is_premium,
'image' => $media->image, 'image' => $media->image,
'category' => $media->category, 'category' => $media->category,
'tags' => $media->tags, 'tags' => $media->tags,
'myNote' => $media->myNote, 'myNote' => $media->myNote,
'is_saved' => $media->is_saved, 'is_saved' => $media->is_saved,
'is_premium' => $media->is_premium, 'statistics' => [
'comments' => $media->comments,
'average_rating' => $media->average_rating, 'average_rating' => $media->average_rating,
'your_rating' => $media->user_rating, 'total_ratings' => $media->ratings_count,
'comments_count' => $media->comments()->count(), 'total_comments' => $media->comments_count,
'rating_distribution' => $media->rating_distribution,
],
'user_interaction' => [
'has_rated' => $media->has_user_rated,
'user_rating' => $media->user_rating,
'has_commented' => $media->has_user_commented,
'user_comment' => $media->user_comment,
'user_comment_id' => $media->user_comment_id,
],
'comments' => $comments,
]); ]);
} }
public function rate(Request $request, $mediaId) public function rate(Request $request, $mediaId)
@@ -0,0 +1,125 @@
<?php
namespace App\Http\Controllers;
use App\Models\MusicPlaylist;
use App\Models\MusicCategory;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
class MusicCategoryController extends Controller
{
public function index()
{
$categories = MusicCategory::with(['image', 'playlists' => function($q) {
$q->where('is_active', true)->orderBy('order');
}])->where('is_active', true)->orderBy('order')->get();
return response()->json($categories);
}
public function store(Request $request)
{
try {
$data = $request->validate([
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'image_id' => 'nullable|exists:images,id',
'order' => 'nullable|integer',
'is_active' => 'nullable|boolean',
]);
// Check for duplicate name
$slug = Str::slug($data['name']);
$existingCategory = MusicCategory::where('slug', $slug)->first();
if ($existingCategory) {
return response()->json([
'message' => 'A category with this name already exists',
'errors' => [
'name' => ['The category name "' . $data['name'] . '" is already taken. Please use a different name.']
]
], 422);
}
// Optional: Check for duplicate name with case-insensitive comparison
$existingName = MusicCategory::whereRaw('LOWER(name) = ?', [strtolower($data['name'])])->first();
if ($existingName) {
return response()->json([
'message' => 'A category with a similar name already exists',
'errors' => [
'name' => ['Category "' . $existingName->name . '" already exists. Please use a different name.']
]
], 422);
}
$data['slug'] = $slug;
$category = MusicCategory::create($data);
return response()->json([
'message' => 'Category created successfully',
'category' => $category->load('image')
], 201);
} catch (\Illuminate\Database\QueryException $e) {
// Handle database duplicate entry error (if unique constraint exists)
if ($e->errorInfo[1] == 1062) { // MySQL duplicate entry error code
return response()->json([
'message' => 'A category with this name already exists',
'errors' => [
'name' => ['The category name must be unique.']
]
], 422);
}
return response()->json([
'message' => 'An error occurred while creating the category',
'error' => $e->getMessage()
], 500);
}
}
public function show($id)
{
$category = MusicCategory::with(['image', 'playlists' => function($q) {
$q->with(['image', 'musics' => function($q2) {
$q2->where('is_active', true)->with('image')->orderBy('order');
}])->where('is_active', true)->orderBy('order');
}])->findOrFail($id);
return response()->json($category);
}
public function update(Request $request, $id)
{
$category = MusicCategory::findOrFail($id);
$data = $request->validate([
'name' => 'sometimes|string|max:255',
'description' => 'nullable|string',
'image_id' => 'nullable|exists:images,id',
'order' => 'nullable|integer',
'is_active' => 'nullable|boolean',
]);
if (isset($data['name'])) {
$data['slug'] = Str::slug($data['name']);
}
$category->update($data);
return response()->json([
'message' => 'Category updated successfully',
'category' => $category->load('image')
]);
}
public function destroy($id)
{
$category = MusicCategory::findOrFail($id);
$category->delete();
return response()->json(['message' => 'Category deleted successfully']);
}
}
+210 -25
View File
@@ -3,23 +3,137 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\MusicPlaylist;
use App\Models\Music; use App\Models\Music;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
class MusicController extends Controller class MusicController extends Controller
{ {
public function index()
{
$userId = auth()->id();
$music = Music::with(['image', 'playlist'])
->where('type', 'public')
->orWhere(function($query) use ($userId) {
$query->where('type', 'private')
->where('user_id', $userId);
})
->orderBy('created_at', 'desc')
->get();
return response()->json([
'data' => $music,
'total' => $music->count()
]);
}
public function getMusicByPlaylist($playlistId)
{
$playlist = MusicPlaylist::findOrFail($playlistId);
$music = Music::where('playlist_id', $playlistId)
->where('is_active', true)
->with(['image', 'tags'])
->orderBy('order')
->get();
return response()->json([
'playlist' => $playlist->load('image'),
'musics' => $music
]);
}
public function addToPlaylist(Request $request, $musicId)
{
$music = Music::where('id', $musicId)
->where(function($q) {
$q->where('type', 'public')
->orWhere('user_id', auth()->id());
})
->firstOrFail();
$data = $request->validate([
'playlist_id' => 'required|exists:music_playlists,id',
'order' => 'nullable|integer',
]);
$music->update([
'playlist_id' => $data['playlist_id'],
'order' => $data['order'] ?? $music->order,
]);
return response()->json([
'message' => 'Music added to playlist successfully',
'music' => $music->load(['image', 'playlist'])
]);
}
public function removeFromPlaylist($musicId)
{
$music = Music::where('id', $musicId)
->where('user_id', auth()->id())
->firstOrFail();
$music->update(['playlist_id' => null]);
return response()->json(['message' => 'Music removed from playlist']);
}
public function updateOrder(Request $request)
{
$data = $request->validate([
'musics' => 'required|array',
'musics.*.id' => 'required|exists:music,id',
'musics.*.order' => 'required|integer',
]);
foreach ($data['musics'] as $item) {
Music::where('id', $item['id'])
->where('user_id', auth()->id())
->update(['order' => $item['order']]);
}
return response()->json(['message' => 'Order updated successfully']);
}
// ✅ Upload music // ✅ Upload music
public function store(Request $request) public function store(Request $request)
{ {
try {
$data = $request->validate([ $data = $request->validate([
'title' => 'required|string|max:255', 'title' => 'required|string|max:255',
'artist' => 'nullable|string|max:255', 'artist' => 'nullable|string|max:255',
'file' => 'required|mimes:mp3,wav,ogg|max:10240', // max 10MB 'file' => 'required|mimes:mp3,wav,ogg|max:20971520',
'type' => 'nullable|in:public,private', 'type' => 'nullable|in:public,private',
'image_id' => 'nullable|exists:images,id', 'image_id' => 'nullable|exists:images,id',
'playlist_id' => 'nullable|exists:music_playlists,id',
'duration' => 'nullable|string|regex:/^(?:\d+:)?[0-5]?\d:[0-5]\d$/', // validates mm:ss or hh:mm:ss
]); ]);
$path = $request->file('file')->store('music', 'public'); // Handle file upload
if (!$request->hasFile('file')) {
return response()->json([
'message' => 'No file was uploaded'
], 400);
}
$file = $request->file('file');
// Validate file size
if ($file->getSize() > 20971520) {
return response()->json([
'message' => 'File size exceeds 10MB limit'
], 422);
}
$path = $file->store('music', 'public');
if (!$path) {
return response()->json([
'message' => 'Failed to store the file'
], 500);
}
$music = Music::create([ $music = Music::create([
'user_id' => auth()->id(), 'user_id' => auth()->id(),
@@ -28,39 +142,46 @@ public function store(Request $request)
'file_path' => $path, 'file_path' => $path,
'type' => $data['type'] ?? 'private', 'type' => $data['type'] ?? 'private',
'image_id' => $data['image_id'] ?? null, 'image_id' => $data['image_id'] ?? null,
'playlist_id' => $data['playlist_id'] ?? null,
'duration' => $data['duration'] ?? null, // Store as string
'order' => $this->getNextOrderInPlaylist($data['playlist_id'] ?? null),
'is_active' => true,
]); ]);
return response()->json([ return response()->json([
'message' => 'Music uploaded successfully', 'message' => 'Music uploaded successfully',
'music' => $music->load('image'), 'music' => $music->load(['image', 'playlist', 'tags']),
'url' => asset('storage/' . $path), 'url' => asset('storage/' . $path),
]); ], 201);
} catch (\Illuminate\Validation\ValidationException $e) {
return response()->json([
'message' => 'Validation failed',
'errors' => $e->errors()
], 422);
} catch (\Exception $e) {
return response()->json([
'message' => 'An error occurred while uploading the music',
'error' => $e->getMessage()
], 500);
}
} }
// ✅ Get all public + user private music // Helper method to get next order number in playlist
public function all() private function getNextOrderInPlaylist($playlistId)
{ {
$userId = auth()->id(); if (!$playlistId) {
return 0;
$music = Music::where('type', 'public')
->orWhere(function($query) use ($userId) {
$query->where('type', 'private')->where('user_id', $userId);
})
->get();
$music = Music::with('image') // eager load image
->where('type', 'public')
->orWhere(function($query) use ($userId) {
$query->where('type', 'private')->where('user_id', $userId);
})
->get();
return response()->json($music);
} }
// ✅ Update music $maxOrder = Music::where('playlist_id', $playlistId)->max('order');
return ($maxOrder ?? -1) + 1;
}
// ✅ Update music with string duration
public function update(Request $request, $id) public function update(Request $request, $id)
{ {
try {
$music = Music::where('id', $id)->where('user_id', auth()->id())->firstOrFail(); $music = Music::where('id', $id)->where('user_id', auth()->id())->firstOrFail();
$data = $request->validate([ $data = $request->validate([
@@ -69,23 +190,87 @@ public function update(Request $request, $id)
'type' => 'nullable|in:public,private', 'type' => 'nullable|in:public,private',
'file' => 'nullable|mimes:mp3,wav,ogg|max:10240', 'file' => 'nullable|mimes:mp3,wav,ogg|max:10240',
'image_id' => 'nullable|exists:images,id', 'image_id' => 'nullable|exists:images,id',
'playlist_id' => 'nullable|exists:music_playlists,id',
'duration' => 'nullable|string|regex:/^(?:\d+:)?[0-5]?\d:[0-5]\d$/',
'order' => 'nullable|integer',
'is_active' => 'nullable|boolean',
]); ]);
if ($request->hasFile('file')) { if ($request->hasFile('file')) {
// Delete old file
Storage::disk('public')->delete($music->file_path); Storage::disk('public')->delete($music->file_path);
$path = $request->file('file')->store('music', 'public'); $path = $request->file('file')->store('music', 'public');
$music->file_path = $path; $music->file_path = $path;
} }
// Update only provided fields
$music->fill($data); $music->fill($data);
$music->save(); $music->save();
return response()->json([ return response()->json([
'message' => 'Music updated successfully', 'message' => 'Music updated successfully',
'music' => $music->load('image'), 'music' => $music->load(['image', 'playlist', 'tags']),
'url' => asset('storage/' . $music->file_path), 'url' => asset('storage/' . $music->file_path),
]); ]);
} catch (\Exception $e) {
return response()->json([
'message' => 'An error occurred while updating the music',
'error' => $e->getMessage()
], 500);
}
}
// ✅ Get all public + user private music
public function show($id)
{
$userId = auth()->id();
$music = Music::with([
'image',
'playlist',
'tags',
'comments' => function($query) {
$query->with('user')->latest()->limit(10);
},
'ratings'
])
->where(function($query) use ($userId) {
$query->where('type', 'public')
->orWhere(function($q) use ($userId) {
$q->where('type', 'private')
->where('user_id', $userId);
});
})
->findOrFail($id);
// Get user's specific comment
$userComment = $music->userComment();
// Get paginated comments for the response
$comments = $music->comments()
->with('user')
->latest()
->paginate(15);
return response()->json([
'music' => $music,
'statistics' => [
'average_rating' => $music->average_rating,
'total_ratings' => $music->ratings_count,
'total_comments' => $music->comments_count,
'rating_distribution' => $music->rating_distribution,
],
'user_interaction' => [
'has_rated' => $music->has_user_rated,
'user_rating' => $music->user_rating,
'has_commented' => $music->has_user_commented,
'user_comment' => $music->user_comment,
'user_comment_id' => $music->user_comment_id,
],
'comments' => $comments,
]);
} }
// ✅ Delete music // ✅ Delete music
@@ -0,0 +1,92 @@
<?php
namespace App\Http\Controllers;
use App\Models\MusicPlaylist;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class MusicPlaylistController extends Controller
{
public function index(Request $request)
{
$query = MusicPlaylist::with(['category', 'image']);
if ($request->has('category_id')) {
$query->where('category_id', $request->category_id);
}
$playlists = $query->where('is_active', true)->orderBy('order')->get();
return response()->json($playlists);
}
public function store(Request $request)
{
$data = $request->validate([
'category_id' => 'required|exists:music_categories,id',
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'image_id' => 'nullable|exists:images,id',
'order' => 'nullable|integer',
'is_active' => 'nullable|boolean',
]);
$data['slug'] = Str::slug($data['name']);
$playlist = MusicPlaylist::create($data);
return response()->json([
'message' => 'Playlist created successfully',
'playlist' => $playlist->load(['category', 'image'])
], 201);
}
public function show($id)
{
$playlist = MusicPlaylist::with([
'category',
'image',
'musics' => function($q) {
$q->where('is_active', true)
->with(['image', 'tags'])
->orderBy('order');
}
])->findOrFail($id);
return response()->json($playlist);
}
public function update(Request $request, $id)
{
$playlist = MusicPlaylist::findOrFail($id);
$data = $request->validate([
'category_id' => 'sometimes|exists:music_categories,id',
'name' => 'sometimes|string|max:255',
'description' => 'nullable|string',
'image_id' => 'nullable|exists:images,id',
'order' => 'nullable|integer',
'is_active' => 'nullable|boolean',
]);
if (isset($data['name'])) {
$data['slug'] = Str::slug($data['name']);
}
$playlist->update($data);
return response()->json([
'message' => 'Playlist updated successfully',
'playlist' => $playlist->load(['category', 'image'])
]);
}
public function destroy($id)
{
$playlist = MusicPlaylist::findOrFail($id);
$playlist->delete();
return response()->json(['message' => 'Playlist deleted successfully']);
}
}
+151
View File
@@ -0,0 +1,151 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RatingController extends Controller
{
/**
* Add or update rating for any model
*
* @param Request $request
* @param string $type (music, media, etc.)
* @param int $id
*/
public function rate(Request $request, $type, $id)
{
$request->validate([
'stars' => 'required|integer|min:1|max:5',
]);
$model = $this->getModel($type, $id);
$this->checkAccess($model);
$rating = $model->ratings()->updateOrCreate(
['user_id' => auth()->id()],
['stars' => $request->stars]
);
return response()->json([
'message' => 'Rating submitted successfully',
'rating' => $rating,
'average_rating' => $model->fresh()->average_rating,
'user_rating' => $rating->stars,
'total_ratings' => $model->fresh()->ratings_count,
]);
}
/**
* Get user's rating for a model
*/
public function getUserRating($type, $id)
{
$model = $this->getModel($type, $id);
$rating = $model->ratings()
->where('user_id', auth()->id())
->first();
return response()->json([
'rating' => $rating ? $rating->stars : null,
]);
}
/**
* Delete user's rating
*/
public function deleteRating($type, $id)
{
$model = $this->getModel($type, $id);
$deleted = $model->ratings()
->where('user_id', auth()->id())
->delete();
return response()->json([
'message' => $deleted ? 'Rating deleted successfully' : 'No rating found',
]);
}
/**
* Get all ratings for a model
*/
public function getRatings($type, $id)
{
$model = $this->getModel($type, $id);
$this->checkAccess($model);
$ratings = $model->ratings()
->with('user')
->latest()
->paginate(20);
return response()->json([
'average' => $model->average_rating,
'total' => $model->ratings_count,
'ratings' => $ratings,
]);
}
/**
* Get top rated items
*/
public function topRated($type)
{
$modelClass = $this->getModelClass($type);
$userId = auth()->id();
$items = $modelClass::with(['image', 'user'])
->withAvg('ratings', 'stars')
->where(function($query) use ($modelClass, $userId) {
if (method_exists($modelClass, 'isAccessible')) {
// Use model-specific access logic
} elseif (property_exists($modelClass, 'type')) {
$query->where('type', 'public')
->orWhere(function($q) use ($userId) {
$q->where('type', 'private')
->where('user_id', $userId);
});
}
})
->having('ratings_avg_stars', '>', 0)
->orderBy('ratings_avg_stars', 'desc')
->limit(10)
->get();
return response()->json($items);
}
private function getModel($type, $id)
{
$modelClass = $this->getModelClass($type);
$model = $modelClass::findOrFail($id);
return $model;
}
private function getModelClass($type)
{
$models = [
'music' => \App\Models\Music::class,
'media' => \App\Models\Media::class,
];
if (!isset($models[$type])) {
abort(404, 'Invalid model type');
}
return $models[$type];
}
private function checkAccess($model)
{
// Check if model has 'type' property (public/private)
if (property_exists($model, 'type') && $model->type === 'private') {
if (auth()->id() !== $model->user_id) {
abort(403, 'You do not have access to this item');
}
}
}
}
+30 -3
View File
@@ -8,17 +8,44 @@ class Comment extends Model
{ {
protected $fillable = [ protected $fillable = [
'user_id', 'user_id',
'media_id', 'commentable_id',
'commentable_type',
'content', 'content',
]; ];
protected $with = ['user'];
public function user() public function user()
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
public function commentable()
{
return $this->morphTo();
}
// For backward compatibility with Media
public function media() public function media()
{ {
return $this->belongsTo(Media::class); return $this->belongsTo(Media::class, 'commentable_id')->where('commentable_type', Media::class);
} }
// For Music
public function music()
{
return $this->belongsTo(Music::class, 'commentable_id')->where('commentable_type', Music::class);
}
// Check if comment belongs to current user
public function getIsOwnerAttribute()
{
return auth()->check() && $this->user_id === auth()->id();
}
// Add timestamps formatted
public function getFormattedCreatedAtAttribute()
{
return $this->created_at->diffForHumans();
}
protected $appends = ['is_owner', 'formatted_created_at'];
} }
+9 -24
View File
@@ -3,9 +3,11 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use App\Traits\HasRatings;
use App\Traits\HasComments;
class Media extends Model class Media extends Model
{ {
use HasRatings, HasComments;
protected $fillable = [ protected $fillable = [
'user_id', 'user_id',
'image_id', 'image_id',
@@ -22,6 +24,12 @@ class Media extends Model
protected $appends = [ protected $appends = [
'average_rating', 'average_rating',
'user_rating', 'user_rating',
'ratings_count',
'comments_count',
'has_user_commented', // Add this
'user_comment', // Add this
'user_comment_id', // Add this
'has_user_rated' // Add this
]; ];
public function image() public function image()
{ {
@@ -68,27 +76,4 @@ public function getIsSavedAttribute()
->where('user_id', auth()->id()) ->where('user_id', auth()->id())
->exists(); ->exists();
} }
public function ratings()
{
return $this->hasMany(Rating::class);
}
public function getAverageRatingAttribute()
{
return round($this->ratings()->avg('stars'), 1);
}
public function getUserRatingAttribute()
{
if (!auth()->check()) return null;
return $this->ratings()
->where('user_id', auth()->id())
->value('stars');
}
public function comments()
{
return $this->hasMany(Comment::class);
}
} }
+35 -10
View File
@@ -4,26 +4,51 @@
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo; // ← Add this
use Illuminate\Database\Eloquent\Relations\BelongsToMany; // ← Add this
use Illuminate\Database\Eloquent\Relations\HasMany; // ← Add this
use Illuminate\Database\Eloquent\Relations\MorphMany; // ← Add this
use App\Traits\HasRatings;
use App\Traits\HasComments;
class Music extends Model class Music extends Model
{ {
use HasFactory; use HasFactory, HasRatings, HasComments;
protected $table = 'music';
protected $fillable = [ protected $fillable = [
'user_id', 'user_id', 'title', 'artist', 'file_path', 'type',
'title', 'playlist_id', 'image_id', 'duration', 'order', 'is_active'
'artist', ];
'file_path', protected $casts = [
'type', // public or private 'duration' => 'string',
'image_id', 'order' => 'integer',
'is_active' => 'boolean',
];
protected $attributes = [
'type' => 'public', // Default value
]; ];
// Relation to user (optional) // Relation to user (optional)
public function user() public function user()
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
protected $appends = ['url', 'image_url']; public function playlist(): BelongsTo
// Accessor for full URL {
return $this->belongsTo(MusicPlaylist::class, 'playlist_id');
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class, 'music_tags');
}
protected $appends = ['url', 'image_url' , 'average_rating', 'user_rating', 'comments_count' , 'has_user_commented', // Add this
'user_comment', // Add this
'user_comment_id', // Add this
'has_user_rated' // Add this];
];
public function getUrlAttribute() public function getUrlAttribute()
{ {
return asset('storage/' . $this->file_path); return asset('storage/' . $this->file_path);
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; // ← Add this
use Illuminate\Database\Eloquent\Relations\HasMany; // ← Add this
class MusicCategory extends Model
{
protected $table = 'music_categories';
protected $fillable = [
'name', 'slug', 'description', 'image_id', 'order', 'is_active'
];
protected $casts = [
'is_active' => 'boolean',
'order' => 'integer',
];
public function playlists(): HasMany
{
return $this->hasMany(MusicPlaylist::class, 'category_id');
}
public function image(): BelongsTo
{
return $this->belongsTo(Image::class);
}
public function getActivePlaylistsAttribute()
{
return $this->playlists()->where('is_active', true)->get();
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; // ← Add this
use Illuminate\Database\Eloquent\Relations\HasMany; // ← Add this
class MusicPlaylist extends Model
{
protected $table = 'music_playlists';
protected $fillable = [
'category_id', 'name', 'slug', 'description', 'image_id', 'order', 'is_active'
];
protected $casts = [
'is_active' => 'boolean',
'order' => 'integer',
];
public function category(): BelongsTo
{
return $this->belongsTo(MusicCategory::class, 'category_id');
}
public function musics(): HasMany
{
return $this->hasMany(Music::class, 'playlist_id');
}
public function image(): BelongsTo
{
return $this->belongsTo(Image::class);
}
public function getActiveMusicsAttribute()
{
return $this->musics()->where('is_active', true)->orderBy('order')->get();
}
public function getTotalDurationAttribute()
{
return $this->musics()->where('is_active', true)->sum('duration');
}
}
+16 -3
View File
@@ -8,17 +8,30 @@ class Rating extends Model
{ {
protected $fillable = [ protected $fillable = [
'user_id', 'user_id',
'media_id', 'rateable_id',
'rateable_type',
'stars', 'stars',
]; ];
public function media() public function rateable()
{ {
return $this->belongsTo(Media::class); return $this->morphTo();
} }
public function user() public function user()
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }
// For backward compatibility with Media
public function media()
{
return $this->belongsTo(Media::class, 'rateable_id')->where('rateable_type', Media::class);
}
// For Music
public function music()
{
return $this->belongsTo(Music::class, 'rateable_id')->where('rateable_type', Music::class);
}
} }
+2 -1
View File
@@ -3,7 +3,8 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; // ← Add this
use Illuminate\Database\Eloquent\Relations\HasMany; // ← Add this
class Tag extends Model class Tag extends Model
{ {
protected $fillable = ['name']; protected $fillable = ['name'];
+67
View File
@@ -0,0 +1,67 @@
<?php
// app/Traits/HasComments.php
namespace App\Traits;
use App\Models\Comment;
trait HasComments
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
// Get user's specific comment
public function userComment()
{
if (!auth()->check()) return null;
return $this->comments()
->where('user_id', auth()->id())
->first();
}
// Check if user has commented
public function getHasUserCommentedAttribute()
{
return !is_null($this->userComment());
}
// Get user's comment content
public function getUserCommentAttribute()
{
$comment = $this->userComment();
return $comment ? $comment->content : null;
}
// Get user's comment id
public function getUserCommentIdAttribute()
{
$comment = $this->userComment();
return $comment ? $comment->id : null;
}
// Get latest comments with user info
public function getLatestCommentsAttribute()
{
return $this->comments()
->with('user')
->latest()
->limit(10)
->get();
}
// Get paginated comments
public function getPaginatedComments($perPage = 15)
{
return $this->comments()
->with('user')
->latest()
->paginate($perPage);
}
public function getCommentsCountAttribute()
{
return $this->comments()->count();
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
// app/Traits/HasRatings.php
namespace App\Traits;
use App\Models\Rating;
trait HasRatings
{
public function ratings()
{
return $this->morphMany(Rating::class, 'rateable');
}
public function getAverageRatingAttribute()
{
return round($this->ratings()->avg('stars'), 1);
}
public function getUserRatingAttribute()
{
if (!auth()->check()) return null;
return $this->ratings()
->where('user_id', auth()->id())
->value('stars');
}
// Get user's rating object
public function userRating()
{
if (!auth()->check()) return null;
return $this->ratings()
->where('user_id', auth()->id())
->first();
}
// Check if user has rated
public function getHasUserRatedAttribute()
{
return !is_null($this->userRating());
}
public function getRatingsCountAttribute()
{
return $this->ratings()->count();
}
// Get rating distribution
public function getRatingDistributionAttribute()
{
$distribution = [];
for ($i = 1; $i <= 5; $i++) {
$distribution[$i] = $this->ratings()->where('stars', $i)->count();
}
return $distribution;
}
}
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('music_categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->foreignId('image_id')->nullable()->constrained('images')->onDelete('set null');
$table->integer('order')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('music_categories');
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('music_playlists', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained('music_categories')->onDelete('cascade');
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->foreignId('image_id')->nullable()->constrained('images')->onDelete('set null');
$table->integer('order')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('music_playlists');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('music', function (Blueprint $table) {
$table->foreignId('playlist_id')->nullable()->constrained('music_playlists')->onDelete('cascade');
$table->string('duration')->nullable();
$table->integer('order')->default(0);
$table->boolean('is_active')->default(true);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('music', function (Blueprint $table) {
$table->dropForeign(['playlist_id']);
$table->dropColumn(['playlist_id', 'image_id', 'duration', 'order', 'is_active']);
});
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('music_tags', function (Blueprint $table) {
$table->id();
$table->foreignId('music_id')->constrained()->onDelete('cascade');
$table->foreignId('tag_id')->constrained()->onDelete('cascade');
$table->timestamps();
$table->unique(['music_id', 'tag_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('music_tags');
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('comments', function (Blueprint $table) {
$table->dropForeign(['media_id']);
$table->dropColumn('media_id');
// Add polymorphic columns
$table->morphs('commentable');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('comments', function (Blueprint $table) {
$table->dropMorphs('commentable');
$table->foreignId('media_id')->constrained()->onDelete('cascade');
});
}
};
@@ -0,0 +1,65 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::dropIfExists('ratings');
Schema::create('ratings', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')
->constrained()
->cascadeOnDelete();
// polymorphic relation
$table->morphs('rateable');
$table->tinyInteger('stars'); // 1-5
$table->timestamps();
// one rating per user per item
$table->unique([
'user_id',
'rateable_id',
'rateable_type'
], 'ratings_user_rateable_unique');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('ratings');
// optional: rollback old structure (if you still need it)
Schema::create('ratings', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')
->constrained()
->cascadeOnDelete();
$table->foreignId('media_id')
->constrained()
->cascadeOnDelete();
$table->tinyInteger('stars');
$table->timestamps();
$table->unique(['user_id', 'media_id']);
});
}
};
+15
View File
@@ -1,3 +1,18 @@
<IfModule mod_php7.c>
php_value post_max_size 128M
php_value upload_max_filesize 128M
php_value max_execution_time 300
php_value max_input_time 300
</IfModule>
<IfModule mod_php8.c>
php_value post_max_size 128M
php_value upload_max_filesize 128M
php_value max_execution_time 300
php_value max_input_time 300
</IfModule>
<IfModule mod_rewrite.c> <IfModule mod_rewrite.c>
<IfModule mod_negotiation.c> <IfModule mod_negotiation.c>
Options -MultiViews -Indexes Options -MultiViews -Indexes
+3
View File
@@ -0,0 +1,3 @@
<?php
phpinfo();
?>
+46 -5
View File
@@ -15,6 +15,11 @@
use App\Http\Controllers\ImageController; use App\Http\Controllers\ImageController;
use App\Http\Controllers\MusicController; use App\Http\Controllers\MusicController;
use App\Http\Controllers\MediaController; use App\Http\Controllers\MediaController;
use App\Http\Controllers\MusicCategoryController;
use App\Http\Controllers\MusicPlaylistController;
use App\Http\Controllers\RatingController;
use App\Http\Controllers\CommentController;
Route::get('/test-hash', function() { Route::get('/test-hash', function() {
$plain = 'amnk1380'; $plain = 'amnk1380';
@@ -120,10 +125,10 @@
/// music /// music
Route::post('/music', [MusicController::class, 'store']); // Route::post('/music', [MusicController::class, 'store']);
Route::get('/music/all', [MusicController::class, 'all']); // Route::get('/music/all', [MusicController::class, 'all']);
Route::put('/music/{id}', [MusicController::class, 'update']); // Route::put('/music/{id}', [MusicController::class, 'update']);
Route::delete('/music/{id}', [MusicController::class, 'destroy']); // Route::delete('/music/{id}', [MusicController::class, 'destroy']);
Route::get('/slider', [SliderController::class, 'index']); // list all sliders Route::get('/slider', [SliderController::class, 'index']); // list all sliders
@@ -148,6 +153,42 @@
Route::get('/media/{id}/comments', [MediaController::class, 'getComments']); Route::get('/media/{id}/comments', [MediaController::class, 'getComments']);
Route::post('/media/{id}/feedback', [MediaController::class, 'submitFeedback']); Route::post('/media/{id}/feedback', [MediaController::class, 'submitFeedback']);
//add note to media
Route::post('/media/{id}/note', [MediaController::class, 'storeNote']); Route::post('/media/{id}/note', [MediaController::class, 'storeNote']);
// Music Categories
Route::apiResource('music-categories', MusicCategoryController::class);
Route::get('public/music-categories', [MusicCategoryController::class, 'index']);
// Music Playlists
Route::apiResource('music-playlists', MusicPlaylistController::class);
Route::get('playlists/by-category/{categoryId}', [MusicPlaylistController::class, 'index']);
// Music
Route::get('music/playlist/{playlistId}', [MusicController::class, 'getMusicByPlaylist']);
Route::post('music/{musicId}/add-to-playlist', [MusicController::class, 'addToPlaylist']);
Route::delete('music/{musicId}/remove-from-playlist', [MusicController::class, 'removeFromPlaylist']);
Route::post('music/update-order', [MusicController::class, 'updateOrder']);
Route::apiResource('music', MusicController::class);
// Generic Rating Routes (works for both music and media)
Route::prefix('ratings')->group(function () {
Route::post('{type}/{id}', [RatingController::class, 'rate']);
Route::get('{type}/{id}/user', [RatingController::class, 'getUserRating']);
Route::delete('{type}/{id}', [RatingController::class, 'deleteRating']);
Route::get('{type}/{id}', [RatingController::class, 'getRatings']);
Route::get('top/{type}', [RatingController::class, 'topRated']);
});
// Generic Comment Routes (works for both music and media)
Route::prefix('comments')->group(function () {
Route::post('{type}/{id}', [CommentController::class, 'addComment']);
Route::get('{type}/{id}', [CommentController::class, 'getComments']);
Route::put('{type}/{id}/{commentId}', [CommentController::class, 'updateComment']);
Route::delete('{type}/{id}/{commentId}', [CommentController::class, 'deleteComment']);
Route::get('most/{type}', [CommentController::class, 'mostCommented']);
});
}); });