In Laravel 5.5 We can set API through resources (https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20), but how can we send STATUS CODE?
Also how should I set status dynamically which is defined in with()
//namespace App\Http\Resources;
//use Illuminate\Http\Resources\Json\Resource;
//class User extends Resource
public function with($request)
{
return [
'status' => 'success',
];
}
Laravel Resource is one of the best features in Laravel. It makes it easy to modify the output of the result. If you're using an API, you need to have a status code to let the front-end know what the status of the request is. You may find a list of HTTP status code over here.
When a new record is created successful, you want to use 201 Created and for updated records one would exepct a 202 Accepted . But Laravel API Resources send 200 OK by default. If you want to change the response, try it this way:
When building APIs with Laravel, it is recommended to use the apiResource () method while defining resourceful routes, this will generate only API specific routes ( index, store, show, update and destroy ).
In essence, resources are simple. They only need to transform a given model into an array. So, each resource contains a toArray method which translates your model's attributes into an API friendly array that can be returned from your application's routes or controllers: * Transform the resource into an array.
You can use the method setStatusCode()
from response()
:
use App\User;
use App\Http\Resources\User as UserResource;
Route::get('/user', function () {
return (new UserResource(User::find(1)))
->response()
->setStatusCode(200);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With