7

I need to alias when I do a Laravel eager loading:

$posts = Post::with(array('images as main_image' => function($query) // do not run
            {
                $query->where('number', '=', '0');

            }))
            ->where('id', '=', $id)
            ->get();

return Response::json($posts);

I need to to this because I want the JSON response like this:

[
  {
    "id": 126,
    "slug": "abc",
    "name": "abc",
    "created_at": "2014-08-08 08:11:25",
    "updated_at": "2014-08-28 11:45:07",
    "**main_image**": [
      {
        "id": 223,
        "post_id": 126
        ...
      }
    ]
  }
]

It is possible?

Makoto
  • 104,088
  • 27
  • 192
  • 230
kurtko
  • 1,978
  • 4
  • 30
  • 47

2 Answers2

5

Perfect! you give me the idea. Finally I've done this:

Post.php

public function main_image()
{
    return $this->hasMany('FoodImage')->where('number','=','0');
}

public function gallery_images()
{
    // for code reuse
    return $this->main_image();
}

PostController.php

$posts = Post::with('main_image', 'gallery_images')                    
            ->where('id', '=', $id)                    
            ->get();
Ahmed Aboud
  • 1,232
  • 16
  • 19
kurtko
  • 1,978
  • 4
  • 30
  • 47
0

I don't think you can do that with Eloquent, but there would be a few work-arounds that might work.

If you are using PHP 5.6, it's possible to alias the function.

use function images as main_image;

If you are using a version of PHP less than that, you can create a main_image() function and have it call images().

public function main_image()
{
    return $this->images();
}
user1669496
  • 32,176
  • 9
  • 73
  • 65