|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers\Api\Home; |
| 4 | + |
| 5 | +use App\Http\Controllers\Controller; |
| 6 | +use Illuminate\Http\Request; |
| 7 | +use App\Models\Share; |
| 8 | +use App\Models\Post; |
| 9 | +use Illuminate\Support\Facades\Auth; |
| 10 | +use App\Traits\ApiTrait; |
| 11 | + |
| 12 | +class ShareController extends Controller |
| 13 | +{ |
| 14 | + use ApiTrait; |
| 15 | + |
| 16 | + public function sharePost(Request $request, Post $post) |
| 17 | + { |
| 18 | + try { |
| 19 | + $user = Auth::user(); |
| 20 | + |
| 21 | + // Create a new share record for the authenticated user and the post |
| 22 | + $share = new Share(); |
| 23 | + $share->user_id = $user->id; |
| 24 | + $share->post_id = $post->id; |
| 25 | + $share->owneruser_id = $post->user_id; // Set the owneruser_id to the original post owner's ID |
| 26 | + $share->save(); |
| 27 | + |
| 28 | + // Increment the shares_count in the posts table |
| 29 | + $post->increment('shares_count'); |
| 30 | + |
| 31 | + $postData = [ |
| 32 | + 'id' => $share->id, |
| 33 | + 'post_id' => $post->id, |
| 34 | + "content" => $post->content, |
| 35 | + "image_path" => $post->image_path, |
| 36 | + 'user_id' => $user->id, |
| 37 | + 'user_name' => $user->name, |
| 38 | + 'user_image' => $user->imageUrl, |
| 39 | + 'owneruser_id' => $post->user_id, |
| 40 | + 'owner_name' => $post->user->name, |
| 41 | + 'owner_image' => $post->user->imageUrl, |
| 42 | + ]; |
| 43 | + |
| 44 | + return $this->data($postData, 'Post shared successfully', 200); |
| 45 | + } catch (\Exception $e) { |
| 46 | + return $this->errorMessage([], 'An error occurred while sharing the post', 500); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + public function removeShare(Share $share) |
| 52 | + { |
| 53 | + $user = Auth::user(); |
| 54 | + |
| 55 | + // Check if the authenticated user owns this share |
| 56 | + if ($share->user_id === $user->id) { |
| 57 | + $post = $share->post; |
| 58 | + |
| 59 | + // Delete the share |
| 60 | + $share->delete(); |
| 61 | + |
| 62 | + // Decrement the shares_count in the posts table |
| 63 | + $post->decrement('shares_count'); |
| 64 | + |
| 65 | + return $this->data(['share_id' => $share->id,'post_id' => $post->id], 'Share removed successfully', 200); |
| 66 | + } |
| 67 | + |
| 68 | + return $this->errorMessage([], 'Share not found', 404); |
| 69 | + } |
| 70 | +} |
0 commit comments