deepu07
4 months ago
829
3
Laravel

Laravel Map function for nested arrays

Posted 4 months ago by deepu07

Hi Mates, in my project I wanna display records by using an intermediate table (pivot). (book ->book_price(pivot)->publishers) somehow It is displaying multiple times as same records. any help on this would be great. thank you!

$book = DB::table('books')
                ->join('book_price', 'book.id', '=', 'book_price.book_id')
                ->join('publishers', 'book_price.publisher_id', '=', 'publishers.id')
                ->select('books.*', 'publishers.id AS publisher_id' )
                ->get()
                ->toArray();

            foreach ($book as $key => $publisher) {
                $book['publisher'] = (collect($publisher->publisher_id))->map(function ($item) {
                    $publisher = Publisher::find($item);
            $item['publisher'] = [];
                    $item['publisher'] = $publisher;

                    return $off;
                });
                $book[$key] = $book;
            }

Expected result

    {
        "status": "success",
        "data": [
            {
                "book_id": 1,
                "book_type": "Music",
                "publisher": [
                    {
                        "id": 1,
                        "name": "ABC",
                        "location": "Ny",
            "created_at" : 2020-02-18 17:18:32
                    },
                    {
                        "id": 2,
                        "name": "DEF",
                        "location": "Nj",
            "created_at" : 2020-02-18 17:18:32
                    },
                    {
                       "id": 3,
                        "name": "EFG",
                        "location": "Chicago",
            "created_at" : 2020-02-18 17:18:32
                    }
                ]
            },
            {
               "book_id": 2,
               "book_type": "Sports"
            }
        ]
    }

Please sign in or create an account to participate in this conversation.