0
votes

I cannot figure out how eager loading works with the following example. This is my current DB with two tables, Quotes: where the general information is stored, and QuotesDetails: where details of each Quote in Quotes is stored.

enter image description here

In models I have the following structures:

Quotes.php

class Quotes extends Model
{


    public function quotesdetails()
    {
        return $this->hasMany('App\QuotesDetails', 'quoteid', 'id');
    }
}

and QuotesDetails.php with the following model:

class QuotesDetails extends Model
{

    public function quotes()
    {
        return $this->belongsTo('App\Quotes', 'id', 'quoteid');
    }
}

I used hasMany (in Quotes) because each quote can have/display 3-4 quotesdetails.

In my controller im using the following query:

$returnquotes = Quotes::with('quotesdetails')->where('id', '=', $quoteid)->get();

In my view im using the following structure:

        @foreach ($returnquotes as $quotes)
            {{$quotes->shipcity }}
            {{$quotes->quotesdetails->service_code }}
        @endforeach

shipcity displays the information with no problems, but service_code is not displayed and gives error.

Honestly I believe it has to work with this schema but I cannot figure out why is not working. My thoughts:

  • in controller: using "with('quotesdetails')" in controller it must establish the relation that appears in Quotes.php with name -> quotedetails that hasmany registries associated in QuotesDetails.php

  • in view: using "$quotes->quotesdetails->service_code" must retrieve the service_code associated to the quotes table (i'm using foreach because quotesdetails can have multiple registries per quote)

  • in model: Im using "hasMany" for Quotes.php because the dependent table is QuotesDetails and "belongsTo" in QuotesDetails.php for the inverse reason.

any help to understand the logic of eager loading with eloquent and laravel appreciated.

1
Have you tried to dd($quotes) to see what quotesdetails it contains? (quotesdetails is probably a collection you need to foreach over too, and since it's a collection, service_code doesn't exist)brombeer
I used echo '<pre>' . print_r($returnquotes, true) . '</pre>'; and all the information was displayed, the information from quotes and from quotesdetails. I dont know why it display results duplicated with tags [attributes:protected] => Array and [original:protected] => Arrays_h
but probably you are right, the problem is that I have a collection in the dependent table. so probably I have to make to loops foreach that collections_h

1 Answers

1
votes

$quotes->quotesdetails is a collection itself (has many) so you need to iterate over it using another foreach:

@foreach ($returnquotes as $quotes)
  {{$quotes->shipcity }}
  @foreach ($quotes->quotesdetails as $quotedetail)
    {{$quotedetail->service_code }}
  @endforeach
@endforeach