D
D
dargezrogue2019-03-27 15:14:25
Laravel
dargezrogue, 2019-03-27 15:14:25

How to output Response for each collection object?

public function view()
    {
        $posts = DB::table('posts')
            ->select('*')
            ->get('*');

        foreach ($posts as $post) {
            echo $post->id.'<br>';
            return Response::json([
                'posts'=>
                [
                    'title'=>$post->title,
                    'datatime'=>$post->datetime,
                    'anons'=>$post->anons,
                    'text'=>$post->text,
                    'tags'=>explode(', ', $post->tags),
                    'image'=>$post->images
                ]
            ]);
        }
}

How to display a response in json format for each $posts collection object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pushkarev, 2019-03-27
@AXP-dev

public function view()
{
    $posts = DB::table('posts')
        ->select('*')
        ->get('*');

    return Response::json([
        'posts' => array_map(function($post) {
            return [
                'title'=>$post->title,
                'datatime'=>$post->datetime,
                'anons'=>$post->anons,
                'text'=>$post->text,
                'tags'=>explode(', ', $post->tags),
                'image'=>$post->images
            ];
        }, $posts)
    ]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question