middleware('auth'); } public function store(Request $request, User $user) { if (Auth::id() !== $user->id) { abort(403); } $request->validate([ 'body' => 'nullable|string|max:2000', 'images' => 'nullable|array|max:10', 'images.*' => 'image|mimes:jpg,jpeg,png,webp,gif|max:8192', 'video_ids' => 'nullable|array|max:10', 'video_ids.*' => 'exists:videos,id', // Legacy fields 'video_id' => 'nullable|exists:videos,id', 'image' => 'nullable|image|mimes:jpg,jpeg,png,webp,gif|max:8192', ]); $hasImages = $request->hasFile('images'); $hasVideoIds = $request->filled('video_ids'); $hasLegacyImg = $request->hasFile('image'); $hasLegacyVid = $request->filled('video_id'); if (! $request->body && ! $hasImages && ! $hasLegacyImg && ! $hasVideoIds && ! $hasLegacyVid) { return back()->withErrors(['body' => 'Post cannot be empty.']); } $data = [ 'user_id' => $user->id, 'body' => $request->body, 'video_id' => $request->video_id ?? null, ]; // Legacy single image (backward compat) if ($hasLegacyImg) { $filename = uniqid('post_', true) . '.' . $request->file('image')->getClientOriginalExtension(); $request->file('image')->storeAs('public/post_images', $filename); $data['image'] = $filename; } $post = Post::create($data); // New multi-image if ($hasImages) { foreach ($request->file('images') as $idx => $file) { $filename = uniqid('post_', true) . '.' . $file->getClientOriginalExtension(); $file->storeAs('public/post_images', $filename); PostImage::create([ 'post_id' => $post->id, 'filename' => $filename, 'sort_order' => $idx, ]); } } // New multi-video if ($hasVideoIds) { foreach ($request->input('video_ids') as $idx => $videoId) { PostVideo::create([ 'post_id' => $post->id, 'video_id' => $videoId, 'sort_order' => $idx, ]); } } return back()->with('toast_success', 'Post shared!'); } public function destroy(Post $post) { if (Auth::id() !== $post->user_id && ! Auth::user()->isAdmin()) { abort(403); } if ($post->image) { Storage::delete('public/post_images/' . $post->image); } // Delete multi-image files foreach ($post->postImages as $postImage) { Storage::delete('public/post_images/' . $postImage->filename); } $post->delete(); return back()->with('toast_success', 'Post deleted.'); } public function react(Post $post) { $user = Auth::user(); $existing = $post->reactions()->where('user_id', $user->id)->first(); if ($existing) { $existing->delete(); $liked = false; } else { $post->reactions()->create(['user_id' => $user->id, 'type' => 'like']); $liked = true; } return response()->json([ 'liked' => $liked, 'count' => $post->reactions()->count(), ]); } }