1

How can i get the Status code while creating an API with laravel5.

Here is what i am trying to do.

return Response::json( array( 'error' => false, 'results' => $results, 'status_code' => 200 etc ));

All i want to change this status code,as it may be 404,201 etc

Khirad Zahra
  • 843
  • 2
  • 17
  • 42

2 Answers2

3

You should set status code as second parameter, so return response like this:

return response()->json($results, 201);
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

You can use a common function like,

public function returnResponse($message, $statusCode)
{
  return response()->json($message, $statusCode);
}

or

public function returnResponse($message, $statusCode)
{
  return response()->json(['message' => $message], $statusCode); 
}

You can call like as ,

$this->returnResponse('ThankYou for use this', 200); //or
$this->returnResponse('There is an error..!!', 422);

You can use above like something, if you can use without function,

return response()->json(['message' => $message], 201);

I hope, it will help you.

Rama Durai
  • 740
  • 6
  • 17
  • I am having issue how do i get $statusCode ? once i get it then i can pass it to a function or use it where else need it? – Khirad Zahra Nov 02 '16 at 07:36
  • @WaqasAli we have a various code, refer some web site and you can fix with that code. ex:- http://www.restapitutorial.com/httpstatuscodes.html – Rama Durai Nov 02 '16 at 07:40