I'm trying to fetch covers of the books that belongs to an author. So far, so good. But it generates a separate query for each book and takes 2 seconds to load a page, I think I'm doing something wrong.

I use eager loading with my comments table (a comment belongs to a user), but since I use polymorphic relations with images table (a image can belong to different kind of other tables, such as user, thing, or group, so I can't use foreign keys in images table since it's not a right convention), I couldn't find a way to achieve the same thing this time.

Image Model

namespace App\Models; use Illuminate\Database\Eloquent\Model; class Image extends Model { public function imageable() { return $this->morphTo(); } }

Person Model (Author)

namespace App\Models; use Illuminate\Database\Eloquent\Model; class Person extends Model { public function books() { return $this->belongsToMany('\App\Models\Thing', 'person_thing'); }

Thing Model (Books)

namespace App\Models; use Illuminate\Database\Eloquent\Model; class Thing extends Model { public function cover() { return $this->morphMany('\App\Models\Image', 'imageable'); } }

Controller

$findBooks = Person::with(array('books' => function($query) { $query->groupBy('original_name'); }))->find(52957); $allbooks = $findBooks->books; return view('frontend.index')->with('allbooks', $allbooks) }

Current View

@foreach($allbooks as $allBooks) @foreach($allBooks->cover as $value) <img class="hund" src="{{$value->link}}" alt=""> @endforeach @endforeach

Image: