D
D
DTX2017-01-21 19:34:12
Laravel
DTX, 2017-01-21 19:34:12

Is there any way to simplify this selection?

Are there no arrow functions in PHP?

$posts = Post::where('user_id', 1)
    ->orderBy('created_at', 'desc')
    ->get();

$res = $posts->map(function ($item, $key) {
    $tags = $item->tags->map(function ($tag) {
       return [
           'id' => $tag->id,
           'name' => $tag->name
       ];
    });
    return [
        'id' => $item->id,
        'user' => $item->user,
        'tags' => $tags,
        'title' => $item->title,
        'type' => $item->type
    ];
});


return response()->json($res);

Or maybe collections have some method that allows you to shorten this?
$tags = $item->tags->map(function ($tag) {
   return [
       'id' => $tag->id,
       'name' => $tag->name
   ];
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WQP, 2017-01-21
@DirecTwiX

See the documentation forscope

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question