As an alias in Laravel Eager Loading
I need an alias when I do Laravel load:
$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 this because I want a 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
...
}
]
}
]
Maybe?
+3
source to share
2 answers
Perfect! you give me this idea. Finally, I did 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:with('main_image')->with('gallery_images')
->where('id', '=', $id)
->get();
+2
source to share
I don't think you can do this with Eloquent, but there would be a few workarounds that might work.
If you are using PHP 5.6, a function alias is possible.
use function images as main_image;
If you are using a lesser PHP version, you can create a function main_image()
and call it images()
.
public function main_image()
{
return $this->images();
}
+1
source to share