Level 122
you would be better off using eloquent as it will give you the nested dataset you want without all the hassle
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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"
}
]
}
Hi @deepu07
Here is the solution but make sure your model has to relationship functions
$output = [ "status" => "success"];
$books = App\Book::with(['publishers', 'book_price'])->get();
foreach ($books as $book) {
$bookData = [
"book_id" => $book->id,
"book_type" => $book->book_type
];
foreach ($book->publishers as $publisher) {
$bookData['publisher'][] = [
'id' => $publisher->id,
'name' => $publisher->name,
'location' => $publisher->location,
'created_at' => $publisher->created_at,
];
}
$output['data'][] = $bookData;
}
return response()->json($output);
Please or to participate in this conversation.