@gaceho1251 You should set combine unique on pivot table (booking_id, voucher_id) to prevent inserting same data again. Then you don't need to retrieve single data.
$table->unique('booking_id', 'voucher_id');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
vouchers table:
| id | code |
| --- | ------------ |
| 1 | Y7Y0H0U4Q0H3 |
| 2 | F2H0I6V8V2I5 |
| 3 | A7N0R2K6E6A8 |
| 140 | I1D3C4Z1B9T9 |
bookings table:
| id | status | created_at |
| ---- | ------ | -------------------- |
| 1 | done | 2022-01-10 00:00:00 |
| 2 | done | 2022-01-10 00:00:00 |
| 3 | draft | 2022-01-10 00:10:00 |
| 1221 | done | 2022-01-10 00:14:00 |
bookings_discount table:
| id | booking_id | voucher_id |
| -- | ---------- | ---------- |
| 1 | 1 | null |
| 2 | 1 | 1 |
| 3 | 2 | 1 |
| 4 | 3 | 140 |
| 5 | 1221 | 140 |
| 6 | 1221 | 140 |
App/Models/Voucher.php
function bookings(): HasManyThrough
{
return $this->hasManyThrough(Booking::class, BookingDiscount::class, 'voucher_id', 'id', 'id', 'booking_id')->orderBy('created_at', 'desc');
}
$voucher = Voucher::find(140);
return $voucher->load('bookings');
Getting a response like this when I call Voucher id - 140:
{
"id": 140,
"code": I1D3C4Z1B9T9
"bookings": [
{
"id": 1221,
"status": "done",
"created_at": "2022-01-10 00:14:00"
},
{
"id": 1221,
"status": "done",
"created_at": "2022-01-10 00:14:00"
},
{
"id": 3,
"status": "draft",
"created_at": "2022-01-10 00:10:00"
}
}
Desired Result:
{
"id": 140,
"code": I1D3C4Z1B9T9
"bookings": [
{
"id": 1221,
"status": "done"
"created_at": "2022-01-14 00:00:00"
},
{
"id": 3,
"status": "draft",
"created_at": "2022-01-10 00:10:00"
}
}
Please or to participate in this conversation.