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.
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.
dd($quotes)
to see whatquotesdetails
it contains? (quotesdetails
is probably a collection you need toforeach
over too, and since it's a collection,service_code
doesn't exist) – brombeer