我正在创建一个项目,用户可以使用闪存卡进行学习。我有一个 API,用户可以从中检索一副纸牌。未通过身份验证的用户仍然可以检索牌组,但其学习进度不会存储在数据库中。
我希望经过身份验证的用户在从 API 检索闪存卡时在响应中接收额外的数据。更具体地说,每张卡片都应该有一个额外的“study_at”字段,其中包含下次学习该卡片的日期。
“study_at”日期存储在名为“card_user”的数据透视表中。
我尝试修改 Card 模型上的 toArray() 方法,但我不知道这是否是正确的方法。
这是 API 端点:
Route::get('/decks', 'DecksController@index');
DecksController
class DecksController extends Controller
{
public function index()
{
$decks = Deck::all();
return new DeckCollection($decks);
}
套牌集合
class DeckCollection extends ResourceCollection
{
public function toArray($request)
{
return parent::toArray($request);
}
}
甲板资源
class DeckResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'cards' => new CardCollection($this->cards),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
卡片收藏
class CardCollection extends ResourceCollection
{
public function toArray($request)
{
return parent::toArray($request);
}
}
卡片资源
这是我想包含“study_at”日期的位置
class CardResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'front' => $this->front,
'back' => $this->back,
// Include 'study_at' date here
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
这是我希望经过身份验证的用户收到的响应:
{
"id": 1,
"name": "Coffee Break French",
"cards": [
{
"id": 1,
"front": "Good morning",
"back": "Bonjour",
"study_at": "2019-05-26T15:00:00.000000Z"
"created_at": "2019-04-14T21:04:05.000000Z",
"updated_at": "2019-04-14T21:04:05.000000Z"
},
{
"id": 2,
"front": "Good afternoon",
"back": "Bonne après-midi",
"study_at": "2019-05-26T15:00:00.000000Z"
"created_at": "2019-04-14T21:04:21.000000Z",
"updated_at": "2019-04-14T21:04:21.000000Z"
},
{
"id": 3,
"front": "My name is John",
"back": "Je m'appelle John",
"study_at": "2019-05-26T15:00:00.000000Z"
"created_at": "2019-04-14T21:04:37.000000Z",
"updated_at": "2019-04-14T21:04:37.000000Z"
}
],
"created_at": "2019-04-14T21:03:38.000000Z",
"updated_at": "2019-04-14T21:03:38.000000Z"
}
最佳答案
要仅在特定条件下包含属性,您应该使用 conditional attributes :
class CardResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'front' => $this->front,
'back' => $this->back,
// Include 'study_at' date here
'study_at' => $this->when(auth()->user(), $this->study_at), // Retrieve your value through eloquent relation
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
关于laravel - 用户通过身份验证时如何在 API 响应中包含额外数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55731378/