Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

slefevre's avatar

find() and with() return all models, instead of single model with children

I'm working on my first Laravel project in 5.1 . I have a model Survey that has related child records defined in the model ScaleQuestions.

I want to create a route where I can look at a single survey and see along with that all of its child scale questions. I've created this route, trying to eager load one survey and all of its children: but it returns all of the survey models:

public function survey($id) {
    $survey = \App\Gt\Lib\Survey::find($id)
        ->with('scale_questions')
        ->get();
    ;
   \dump($id);
    \dump($survey);
    return view('gt/admin/survey')->with('survey',$survey);

There are (currently) 43 surveys, and only 10 child scale questions, but the dump clearly shows me it loaded the 43 surveys.

Collection {#684 ▼
  #items: array:43 [▼
    0 => Survey {#208 ▶}
    1 => Survey {#209 ▶}
    2 => Survey {#210 ▶}
    3 => Survey {#211 ▶}

When I take out get(), I get a builder object, which I don't know what to do with:

Builder {#161 ▼
  #query: Builder {#154 ▶}
  #model: Survey {#165 ▶}
  #eagerLoad: array:1 [▶]
  #macros: []
  #onDelete: null
  #passthru: array:10 [▶]
}

It seems that it's an unprocessed query, since I can't get any properties off of it:

public function survey($id) {
    $survey = \App\Gt\Lib\Survey::find($id)
        ->with('scale_questions');
        \dump($survey->id);

Gives me this:

ErrorException in AdminSurveysController.php line 31: Undefined property: Illuminate\Database\Eloquent\Builder::$id

How do I eager-load the single survey and only its child questions?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Put the find($id) at the end of the chain.

    $survey = \App\Gt\Lib\Survey::with('scale_questions')->find($id);
jekinney's avatar

You can also lazy eager old with load() after you get a collection but with() should always be first as @tykus_ikus example.

Please or to participate in this conversation.