Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DannyCooper's avatar

Extra query when lazy-loading relationship

I'm testing a simple example and can't understand why the second select * from data is needed/executed when the data is already returned by the first query. Could anybody offer any insights?

Thanks!

Image

Route::get('product/{slug}', function ($slug) {
    $product = Product::where('slug', $slug)->with('Data')->first();
    $data = $product->data;
    return view('product');
});
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    public function data()
    {
        return $this->hasMany('App\Models\Data');
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Data extends Model
{
    use HasFactory;

    public function product()
    {
        return $this->belongsTo('App\Models\Product');
    }
}
0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try using the correct case

Route::get('product/{slug}', function ($slug) {
    $product = Product::where('slug', $slug)->with('data')->first();
    $data = $product->data;
    return view('product');
});
 
1 like
DannyCooper's avatar

Thank you @Sinnbeck! I'm new to Eloquent so I thought it wanted the Model name capitalized as it is when the Model is instantiated, and because it didn't fail I didn't double-check that.

Please or to participate in this conversation.