I would personally go with the first one, as it follows the Single responsibility principle, and it uses crud principles
Oct 22, 2020
2
Level 13
laravel controller methods naming convention alternatives
I have a FollowController and i want to
- get list of user that a user follows ( following )
- get list of users that a user is followed by ( followers )
However i can't do that in the same controller without breaking the naming convention or without introducing if statements in the controller.
I would like to know your opinion on this.
First Approach
Create separate controllers
class FollowersController extends Controller
{
public function index(User $user)
{
return $user->followedBy;
}
}
class FollowingController extends Controller
{
public function index(User $user)
{
return $user->follows;
}
}
Second Approach
Break the naming convention and fit both in the same controller
class FollowController extends Controller
{
public function followedBy(User $user)
{
return $user->followedBy;
}
public function follows(User $user)
{
return $user->follows;
}
}
Third Approach
Use a flag to decide whether to return either one or both ( in this case 1 extra request is avoided and you serve both in a single request )
class FollowControllerr extends Controller
{
public function index(User $user)
{
if (request()->boolean('follows'))
{
return $user->follows;
}
elseif (request()->boolean('followedBy'))
{
return $user->followedBy;
}
return [
'follows' => $user->follows,
'folllowedBy' => $user->followedBy
];
}
}
Please or to participate in this conversation.