Skip to content

Commit 010f68c

Browse files
get all posts for user
1 parent f8d079d commit 010f68c

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

app/Http/Controllers/Api/PostController.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,4 +141,31 @@ public function deletePost($id)
141141
$post->delete();
142142
return $this->successMessage('Post deleted successfully', 200);
143143
}
144+
145+
public function getUserPosts($userId)
146+
{
147+
// Find the user by their ID
148+
$user = User::find($userId);
149+
150+
if (!$user) {
151+
return $this->errorMessage([], 'User not found', 404);
152+
}
153+
154+
// Retrieve all posts for the user with the user relationship
155+
$posts = $user->posts()->orderBy('created_at', 'desc')->get();
156+
157+
// Transform the posts data to include user_name and user_imageUrl
158+
$postData = $posts->map(function ($post) {
159+
$data = $post->toArray();
160+
$data['user_name'] = $post->user->name; // Change 'name' to the actual column name in your users table
161+
$data['user_imageUrl'] = $post->user->imageUrl; // Change 'imageUrl' to the actual column name in your users table
162+
unset($data['user']); // Remove the user relationship to avoid redundancy
163+
return $data;
164+
});
165+
166+
return $this->data(compact('postData'));
167+
}
168+
169+
170+
144171
}

routes/api.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@
100100
Route::get('/show/{id}', 'showPost');
101101
Route::post('/edit/{id}', 'editPost');
102102
Route::post('/delete/{id}', 'deletePost');
103+
Route::get('/user/{id}', 'getUserPosts');
104+
103105
});
104106

105107
// --------------------------------- Comment Controller ------------------------------------------

0 commit comments

Comments
 (0)