0

In my Property Model I have these two relationships defined

public function images() {
    return $this->hasMany('Image')
        ->where('approved', '=', 1);
}
public function pending_images() {
    return $this->hasMany('Image')
        ->where('approved', '=', 0);
}

In my Controller, I create a Property object and try to fetch both the approved and pending images.

$images = $property->images;
$pending = $property->pending_images;

var_dump($images);
var_dump($pending);
exit;

The $images variable is a Illuminate\Database\Eloquent\Collection as expected.

However, $pending is just NULL!

I try fetching the last DB query, using this answer, and it seems that the pending query is not even being executed. (The last query run has approved = 1, which is for the images relationship.)

My suspicion is that it might be a problem that the relationship is on the same table but I'm stumped.

Community
  • 1
  • 1
andrewtweber
  • 24,520
  • 22
  • 88
  • 110

1 Answers1

3

You need to rename that relation to camelCase:

public function pendingImages() {
   return $this->hasMany('Image')
     ->where('approved', '=', 0);
}

Then it will work as expected, moreover you will be able to access it either way:

$property->pending_images == $property->pendingImages;

Dynamic properties work only with camelCased methods, that's all.

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157