1

I'm building a REST API in Laravel and when a new user is created I want to return a 201 status code and a Location header to point to the new resource.

Most of that is being achieved using this code:

$response = Response::make(null, 201)->header('Location', Config::get('app.url') . '/v1/users/' . $user->id);
return $response;

However Laravel seems to be overriding what I set as the status code because I'm setting a Location header, as I'm getting a 302 Moved Temporarily header back.

How can I force a 201 status code even when I'm specifying a Location header?

1
  • Fair play for implementing proper response codes. I really don't know why Laravel (which I have huge respect for) doesn't encourage returning "201 Created" for success in the Create method by default. Good work! Commented Oct 16, 2017 at 15:51

1 Answer 1

2

The problem is when you set the header() location, it is overwriting the Laravel response.

If you add 201 status to the header() function - it should work I think:

$response = Response::make(null, 201)->header('Location', Config::get('app.url') . '/v1/users/' . $user->id, true, 201);
return $response;
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant thanks, wasn't aware the header() method took those extra parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.