I'm converting a site to Laravel. It's a giant site and unfortunately, I can't rename existing columns because of the ripple effect. We're only converting the public-facing pages and leaving the back-end as-is for the time being. So, we need to preserve the column names, etc. This is posing some problems, but it's a requirement of the project. I know that these aren't standard column names and that may be causing a problem. But I've inherited it and need to do make it work.
I'm eager loading some results and getting the error "Invalid argument supplied for foreach()".
Here is the controller:
$show = Show::with(array('demos' => function($demo_query)
{
$demo_query->where('rec_class', '=', 'D')
->orderby('rec_year');
}))
->with('trivia')
->with(array('versions' => function($version_query)
{
$version_query->orderby('versionyear');
}))
->with(array('other_titles' => function($title_query)
{
$title_query->orderby('sorttitle');
}))
->with('related')
->with('main_title')
->with('links')
->where('showid', '=', $id)
->first();
Here is the model:
public function versions()
{
return $this->hasMany('Version', 'showident', 'showid');
}
And here is the part of the view that I'm having problems with:
@if(0<>count($show->versions))
@foreach($show->versions as $version)
results here
@endforeach
@endif
Can anyone see why I'm getting the error?
First things first, have you dd($show->versions)
to see if it does contain any data?
I already did that. And it contains data. That's what's puzzling.
and the dd says that $show->versions is a collection ?
Sorry, I'd done a var_dump. A dd gives me:
string(1) "1"
Hello. I can't find the error, but I have some tips.
Don't use count($show->versions). count is intended for arrays, not collection. I think count($show->versions) allways returns 1. Use $collection->count() instead.
Make dd($show);
Remove all other eager loaded things to see if it helps (probably not).
Eager loading reduces the number of queries made to the database. This increases performaces. But, if you eager load relations of only one entity, that doesn't reduce the number of queries. Eager loading queries each relation seperate. So, actually, you could remove all that eager loading and if you need something you will get it with a simple $model->relation;
Thanks, Firtzberg.
Well I'm loading those results on their own, not eager loading, and it works just fine.
What would be the reason for that?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community