Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel eloquent resources api send status code

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',
    ];
}
like image 659
user7498776 Avatar asked Nov 15 '17 16:11

user7498776


People also ask

How to get status code of a request in Laravel?

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.

What is the default response for Laravel Records created and updated?

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:

What is apiresource() method in Laravel?

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 ).

What is a resource in Laravel?

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.


1 Answers

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);
});
like image 189
Samuel Martins Avatar answered Oct 17 '22 09:10

Samuel Martins