1
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?

Laravelのレスポンスが [] になる時の対処法

Last updated at Posted at 2025-06-03

今回はCRUD処理だけなので、各種Controllerを共通化するためモデルを as Model にしてコピペで量産するようにしていました。変数名もそれに合わせて $model としましたが取得結果が[] しか返ってこなくなりました..

結果として、Controllerメソッドの変数名がメソッドインジェクションに対応する変数名(単数系キャメルケースのモデル名)になっていないと [] が返るようです。

そんなもの実装に依存させるな..

showメソッドの例

<?php

namespace App\Http\Controllers;

use App\Models\User as Model; // <-- 共通化しようとした
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display the specified resource.
     */
-    public function show(Model $model)
+    public function show(Model $user)
    {
-        return $model; // -> []
+        return $user; // -> {id: 1, name: 'hogemoge', ...}
    }
}

Laravelは初学者の教科書としては良いですが、大きなお世話が過ぎます。
今回の異変に関しても、メソッドインジェクションはコード上から追えない「ミッシングリンク」になっている実装(良く言えば隠匿された実装)なので、StackOverflow に記事がなければ数日解決できない可能性が高かったです。
弊社も今の作業が終われば完全に Laravelフリー な環境になるのですが、最後の最後に一矢報われました…

1
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
1
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?