0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Laravel8.x]APIResourceのwhenLoadedで初期値を設定する

Last updated at Posted at 2022-03-15

APIResourceでリレーションの初期値の設定で割とハマったのでメモ。

やりたかったこと

リレーション先のUserモデルが存在しない時に、Userモデルの空インスタンスをデフォルト値に設定したかった。
ただ、下記のソースだとwhenLoadedの第二引数($value)で無限ループが発生してしまう。

❌  無限ループが発生する
new UserResource($this->whenLoaded('user', $this->user, new User()))

解決

whenLoadedの第二引数($value)にも、whenLoadedを指定することで解決しました。

⭕  
new UserResource($this->whenLoaded('user', $this->whenLoaded('user'), new User()))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?