Search code examples
phplaravelrelationships

Laravel 4: How to access data from belongsTo() relationship?


// models:
class Hometype extends Eloquent {
    public function development() {
        return $this->belongsTo('Development');
    }
}

class Development extends Eloquent {
    public function hometypes() {
        return $this->hasMany('Hometype', 'dev_id');
    }
}

with that, I can do:

// controller:
$development = Development::where('stuff')->first();
// view:
@foreach ($development->hometypes as $hometype)
    {{ $hometype->stuff }}
@endforeach

which is perfectly lovely.

but I can't seem to do:

// controller:
$hometype = Hometype::where('stuff')->first();
// view:
{{ $hometype->development->stuff }} // <- fails

How do I access a field on the parent Development model from within $hometype?

I'm resorting to:

'development' => Development::find($hometype->dev_id),

which seems silly.

Possible duplicate of: Laravel 4 - Can't retrieve data in a one-to-many relationship, but I'm not camelCasing...

Also similar to: Laravel 4 hasOne / belongsTo relationship (no answers here)


Solution

  • As I can see, there might be two problems:

    1. The foreign key in Hometype is wrong (if you're using a different column name than "column"_id then you have to specify it)
    2. You might be fetching a Hometype record whose development row doesn't exist