2017-11-15 7 views
0

Laravel 5.5ではリソース(https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20)でAPIを設定できますが、STATUS CODEはどのように送信できますか?laravel eloquent resources apiステータスコードを送信

あなたが受信/送信されたデータでそれを取得する必要はありませんので、また、私は)デフォルトでは

//namespace App\Http\Resources; 

//use Illuminate\Http\Resources\Json\Resource; 

//class User extends Resource 

public function with($request) 
{ 
    return [ 
     'status' => 'success', 
    ]; 
} 

答えて

0

を(とで定義されている動的にステータスを設定する方法を、HTTP応答が..ステータスコードが含まれますHTTP応答ヘッダーに含まれています。例えば

あなたはAJAXリクエストを送信するためにaxiosを使用している場合、あなたはちょうどあなたがあなたのコントローラでabort(404);を使用するときに、ステータスコードが404になります。..

axios.get('/path/to/get/your/data/'). 
    then(function(response) { 
    // response.status will represent your status code 
}); 

ような何かを行う必要があります。また、内部エラー(コード500)が発生した場合は、応答コードとして500を取得します。

+0

私もajaxを使用していません。201、403などのコードを送信する必要があります。 – user7498776

+0

何のために使用しますか?私はあなたもそれを使用することができると思う –

1

これを試してみてください。

$resource = new UserResource($user); 
return $resource->response()->setStatusCode(200); 
+0

APIリソースでnull要求を処理するとにかくありますか? –

+0

返信[ 'name' =>オプション($ this-> username)、 'email' =>オプション($ this-> email) ]; –

1
namespace App\Http\Resources; 

use Illuminate\Http\Resources\Json\Resource; 

class UserFail extends Resource{ 


/** 
* Customize the outgoing response for the resource. 
* 
* @param \Illuminate\Http\Request 
* @param \Illuminate\Http\Response 
* @return void 
*/ 
public function withResponse($request, $response) 
{ 
    /** 
    * Not all prerequisites were met. 
    */ 
    $response->setStatusCode(428, 'Precondition Required'); 
} 

    public function with($request){ 
     return [ 
     'status'=>'failed' 
     ]; 
    } 

} 

がちょうど

1

あなたはresponse()からメソッドsetStatusCode()を使用することができ、あなたのwithResponse方法であなたのステータスコードを設定します:コントローラで

namespace App\Http\Resources; 

use Illuminate\Http\Resources\Json\Resource; 

class User extends Resource{ 


    public function toArray($request) 
    { 
       return[ 
        'name' => $this->username, 
        'email'=> $this->email 
       ]; 
    } 

    public function with($request){ 
     return [ 
     'status'=>'success' 
     ]; 
    } 

} 

use App\User; 
use App\Http\Resources\User as UserResource; 

Route::get('/user', function() { 
    return (new UserResource(User::find(1))) 
       ->response() 
       ->setStatusCode(200); 
});