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

drldejacto's avatar

Eager Loading results has no collection from related tables

My Model

Document Model


    public function details(){
        return $this->hasMany('App\Details','document_number');
    }

Details Model

    public function document(){
        return $this->belongsTo('App\Document','document_number');
    }

Controller

$user = Auth::user();
      $document = Document::with(['details' => function ($query) use ($user){
          $query->where('status',1)->where('received_by',$user->id);
      }])->where('particulars','like','%'.$request->particulars.'%')->get();

      $document_count = $document->count();
      dd($document);
Collection {#358 ▼
  #items: array:6 [▼
    0 => Document {#367 ▼
      #table: "document"
      #fillable: array:15 [▶]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:17 [▶]
      #original: array:17 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "details" => Collection {#366 ▼
          #items: []
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => Document {#368 ▶}
    2 => Document {#369 ▶}
    3 => Document {#370 ▶}
    4 => Document {#371 ▶}
    5 => Document {#372 ▶}
  ]
}

details Collection has 0 items.

0 likes
3 replies
ftiersch's avatar

Simple question first:

Are there any details with a status = 1 and received_by = current user for that document? Because the code looks fine

ftiersch's avatar

@DRLDEJACTO - No, it has 6 arrays because there are 6 Documents. But do those Documents have Details with the given conditions?

with() is not a clause, it includes it. If you want to see only documents that have details with the given conditions you need to use has()

Please or to participate in this conversation.