I'm developing a social media project using Laravel. I need to provide a customized API for Follows and Followers. Accordingly, I want to establish a relationship between the user table and the followers and followed tables. I have looked at a lot of resources but get confused. Can anyone help me with relationships?
Models
Users: id, username, email, password
Follows: id, user_id, follow_id(user_id)
Followers: id, user_id, follower_id(user_id)
API Url: http://localhost/api/follows/user_id/1
FollowController
public function user_follow($user_id)
{
$user_find = Follows::where("user_id", "=", $user_id)->get();
return response()->json($user_find, 201);
}
Output
[
{
"id": 4,
"user_id": 1,
"follow_id": 4,
"created_at": "2020-03-23T15:11:48.000000Z",
"updated_at": "2020-12-11T11:10:10.000000Z"
},
{
"id": 5,
"user_id": 1,
"follow_id": 1,
"created_at": "2012-08-30T20:16:51.000000Z",
"updated_at": "2020-12-11T11:10:10.000000Z"
}
]
API that brings relevant followed people according to user request. But here, I want to give additional user information of the relevant users, how do I do this?
The most right implementation for me looks like this:
First you do not need two separate tables for tracking follow actions. With one table you can have both.
Then in the model you can do something like:
And in the API you can do:
• To get additional information from the related model, I think you could do a 'leftJoin'.
Something like that
Edit: Another approach for the followers method is to use the 'hasManyThrough' method of the base Model's class.
This way this method returns User models