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

rearmustak's avatar

How to send a header with laravel api response?

I need to set a header with my API response.

In my api controller, I tried to send a header with my response like this.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return Blog::all()->header('X-Total-Count', Blog::all()->count());
}

How to send this properly?

0 likes
2 replies
realrandyallen's avatar
Level 44

Just wrap it in a response:

return response(Blog::all())->header('X-Total-Count', Blog::all()->count());

Consider saving the blog's in a variable and then counting the variable - the way you're doing it now runs the same query twice

1 like

Please or to participate in this conversation.