A
A
Alexander Koregin2020-02-22 13:59:18
Laravel
Alexander Koregin, 2020-02-22 13:59:18

How to display all fields in response?

There is a task

5e5108ea1ee5d058570629.png

I got all the fields from the database

5e510929d5365946753926.png

I'm trying to display, but it doesn't work, it returns only the first field

Here is the code itself

public function getPhotos() {
        $photos = DB::table('photo')
            ->join('share', 'photo.id', '=', 'share.photo_id')->get();
        $jsonPhotos = json_decode($photos , true);

        dd($jsonPhotos);

        for ($i = 0; $i < count($jsonPhotos); $i++) {
            return response()->json(['id' => $jsonPhotos[$i]['id'], 'title' => $jsonPhotos[$i]['title'], 'url' => 'http://photoservice.ru/' . $jsonPhotos[$i]['path'], 'owner_id' => $jsonPhotos[$i]['owner_id'], 'users' => $jsonPhotos[$i]['user_id']], 200);
        }
    }


Must be an array of objects

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Koregin, 2020-02-22
@dragonika8

public function getPhotos() {
        $photos = \DB::table('photo')
            ->join('share', 'photo.id', '=', 'share.photo_id')
            ->get()
            ->groupBy('photo_id')
            ->map(function ($photo) {
                return [
                    'id' => $photo[0]->photo_id,
                    'title' => $photo[0]->title,
                    'url' => 'http://photoservice.ru/' . $photo[0]->path,
                    'owner_id' => $photo[0]->owner_id,
                    'users' => $photo->pluck('user_id')
                ];
            })->values();

        return response()->json($photos, 200);

    }

D
Dmitry, 2020-02-27
@dlnsk

https://laravel.com/docs/6.x/eloquent-resources

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question