1

in my one of models such as posts i have a column array as featured_image and when i get result query from this model that return all of this array items, for example:

"featured_image": {
    "images": {
        "original": "/uploads/post_images/2020/1598873165.jpg",
        "300": "/uploads/post_images/2020/300_1598873165.jpg",
        "900": "/uploads/post_images/2020/900_1598873165.jpg"
    },
    "thumbnail": "/uploads/post_images/2020/300_1598873165.jpg"
},

now how can i modify this below query to get only one item from this array such as thumbnail?

public function allData()
{
    $posts = Post::with(['groups', 'categories' => function ($query) {
        $query->whereLocked(false);
    }])->wherePublished(true)->get();
    return response()->json([
        'posts' => $posts,
    ], 200);
}
8
  • featured_images is a relation or what? Commented Aug 31, 2020 at 18:22
  • @FelippeDuarte featured_image is a column on Posts model Commented Aug 31, 2020 at 18:22
  • You have a JSON stored in this column? Commented Aug 31, 2020 at 18:25
  • @FelippeDuarte yes, thats right, like with pasted output in post Commented Aug 31, 2020 at 18:29
  • You'll probably have to use a join() (or similar) to extract featured_image->thumbnail to a column, then pass forward in your response. You could iterate $posts and do $post->thumbnail = $post->feature_image->thumbnail;, but that's potentially quite slow. Commented Aug 31, 2020 at 18:33

1 Answer 1

1

you can try this :

public function allData()
{
    $posts = Post::with(['groups', 'categories' => function ($query) {
        $query->whereLocked(false);
    }])->wherePublished(true)
    ->select('{primary must included to use With}', 'other', 'columns', 'featured_image->thumbnail as thumbnail')
    ->get();
    return response()->json([
        'posts' => $posts,
    ], 200);
}
Sign up to request clarification or add additional context in comments.

3 Comments

One quick fix, featured_image->thumbnails would be featured_image->thumbnail (no 's', not pluralized)
No problem! And you tag like this: @TimLewis (@ before my username, with no spaces), but I got notified anyway (if only 1 person has commented, they are notified)
@AlzafanChristian how about relationships? such as 'groups', 'categories', i don't have them in output of query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.