Level 24
According to https://laravel.com/docs/5.7/responses#attaching-headers-to-responses
$blog = Blog::all();
return response()->json($blog)->withHeaders(['X-Total-Count', $blog->count()]);
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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?
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
Please or to participate in this conversation.