To achieve eager loading of media items with the Spatie MediaLibrary package, you can use the load method to load media for each house after retrieving the houses with their owners. Unfortunately, the getMedia method doesn't work directly with Eloquent's with method because it's not a traditional Eloquent relationship. However, you can still optimize your queries by using the load method after fetching the houses.
Here's how you can modify your controller to include media for each house:
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Models\House;
use Inertia\Inertia;
class HouseController extends Controller
{
public function show()
{
// First, retrieve houses with their owners
$houses = House::with('owner')->get();
// Then, load media for each house
$houses->load('media');
// Alternatively, you can map over the collection to include media URLs
$housesWithMedia = $houses->map(function ($house) {
$house->media_urls = $house->getMedia('images')->map(function ($media) {
return $media->getUrl('thumb');
});
return $house;
});
return Inertia::render('HousePage', [
'houses' => $housesWithMedia,
]);
}
}
In this solution:
- We first retrieve the houses with their owners using
with('owner'). - We then use the
loadmethod to load the media for each house. - We map over the collection to add a
media_urlsattribute to each house, which contains the URLs of the media items.
This approach avoids running queries in a foreach loop and efficiently loads the necessary data.