OurBG
OurBG

Reputation: 597

Laravel eager loading a BelongsTo relation doesn't work

This seems extremely simple and yet it doesn't work:

// Reservations
class Reservation extends Model
{
    public function service()
    {
        return $this->belongsTo('App\Landing');
    }
}

// Service
class Landing extends Model
{
    public function reservation()
    {
        return $this->hasMany('App\Reservation');
    }
}

And then in my controller I have:

$x = Reservation::with('service')->get();
$y = Reservation::all()->load('service');

None of these work. I've tried several ways of loading it and none of them work. It always returns an empty result for the service.

Any other result works fine with eager loading (even with nesting) except te BelongsTo - this one.

Upvotes: 0

Views: 1479

Answers (1)

Yannick Y
Yannick Y

Reputation: 2846

The eager loading works. The problem is your relationship

When you define a BelongsTo relationship you need to specify a foreign key if the name of your property does not correspond to the entity being referenced

For example: if you call the relationship "landing", you will be fine, because under-the-hood, Laravel passes the foreign key landing_id based on the name of the property

class Reservation extends Model
{   //landing correspond to the lowercase (singular) name of the Landing class
    //in that case Laravel knows how to set the relationship by assuming
    //that you want to match landing_id to the id of the landings table
    public function landing()
    {
        return $this->belongsTo(Landing::class);
    }
}

If you chose to name the relationship differently, such as "service", then you need to specify the foreign key ex: landing_id since service and landing are two different words, and landing correspond to the lowercase version of the actual class Landing. Otherwise Laravel would think your foreign key is "service_id" instead of landing_id

class Reservation extends Model
{
   //service is a custom name to refer to landing 
   //in that case Laravel needs you to specify the foreign key
    public function service()
    {
        return $this->belongsTo(Landing::class, 'landing_id');
    }
}

Read more here: https://laravel.com/docs/5.8/eloquent-relationships#updating-belongs-to-relationships

Upvotes: 1

Related Questions