Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shaungbhone's avatar

Laravel Api with next js app

I'm trying to create laravel api with the NEXT JS app. In my app, users can support the horse. On the listing page, authentication can see horses, and this user can see his supported horse. So, I made this code.

HorseController

public function index() {
		$horses = Horse::addSelect([
            		'supported_by_user' => Support::select('id')
                		->where('user_id', auth()->id())
                		->whereColumn('horse_id', 'horses.id'),
        		])->withCount('users');
}
public function store(Request $request, Horse $horse) {
		$hasSupported = $horse->supported_by_user;
        $support_counts = auth()
            ->user()
            ->count();
        if ($hasSupported) {
            auth()
                ->user()
                ->supports()
                ->detach($request->horse_id);
            $support_counts--;
            $hasSupported = false;
        } else {
            auth()
            ->user()
            ->supports()
            ->attach($request->horse_id);
            $support_counts++;
            $hasSupported = true;
        }
}

The problem is $horse->supported_by_user gives me null.

0 likes
5 replies
martinbean's avatar

@shaungbhone Please have a read over the Eloquent relationships chapter of the Laravel docs. That code is woefully inefficient and will give you N+1 problems.

  • You’re also not actually returning anything from your index action.
  • You don‘t need to use the auth helper to get the authenticated user. You can get them from the request instance using $request->user() (so long as the route is behind auth middleware).
1 like
shaungbhone's avatar

@martinbean Yes I'll refactor the code later. I forgot to add my return code. Here is update.

$horses = Horse::addSelect([
            'supported_by_user' => Support::select('id')
                ->where('user_id', auth()->id())
                ->whereColumn('horse_id', 'horses.id'),
        ])
            ->withCount('users')
            ->get();
return HorseResource::collection($horses);
martinbean's avatar

@shaungbhone Why write unoptimised code just for the sake of re-factoring later? Why not just model your relations properly from the get-go?

It doesn’t make sense to write a “bad” version, just to rewrite it as a “good” version later.

martinbean's avatar

@shaungbhone I don’t really understand what that has to do with anything? A client gives you problems, and then you write the code to solve those problems.

You don’t need a client to tell you when and when you can’t use relations in Eloquent models. Otherwise that client may as well write the code themselves in they know exactly what they want.

1 like

Please or to participate in this conversation.