You cannot get what you want with eloquent, as it will need the foreign_key and primary_id to match the data fetched.
So you need to retrieve more column that you want.
Why don't you want to use your join query, if it works ?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Okay, I have User model with:
public function cars()
{
return $this->hasMany(Car::class);
}
Car model with:
public function user()
{
return $this->belongsTo(User::class);
}
public function bookings()
{
return $this->hasMany(Booking::class);
}
Booking Model with:
public function car()
{
return $this->belongsTo(Car::class);
}
public function service()
{
return $this->belongsTo(Service::class);
}
Service model with:
public function bookings()
{
return $this->hasMany(Booking::class);
}
I've menaged to get multidimensional array like
{
"id": 4,
"plate": "PNB-238",
"manufacturer": "Soyat",
"model": "Yuejin",
"year": 2005,
"kilometrage": 269751,
"hp": 256,
"cc": 1768,
"user_id": 2,
"created_at": "2019-02-11 15:57:24",
"updated_at": "2019-02-11 15:57:24",
"bookings": [
{
"id": 1,
"car_id": 4,
"service_id": 6,
"start_time": "2019-05-20 23:57:24",
"end_time": "2019-05-20 23:57:24",
"created_at": "2019-02-11 15:57:24",
"updated_at": "2019-02-11 15:57:24",
"service": {
"id": 6,
"name": "ipsa voluptas quia",
"cost": 8845,
"time_required": "08:46:00",
"warranty": 9841,
"created_at": "2019-02-11 15:57:24",
"updated_at": "2019-02-11 15:57:24"
}
},
{
"id": 3,
"car_id": 4,
"service_id": 8,
"start_time": "2019-03-16 22:57:24",
"end_time": "2019-03-16 22:57:24",
"created_at": "2019-02-11 15:57:24",
"updated_at": "2019-02-11 15:57:24",
"service": {
"id": 8,
"name": "molestiae esse voluptatibus",
"cost": 9646,
"time_required": "11:40:00",
"warranty": 6797,
"created_at": "2019-02-11 15:57:24",
"updated_at": "2019-02-11 15:57:24"
}
}
]
},
How I can get one-dimensional array of this. I managed to do that with
$now = Carbon::now();
$bookings = Booking::join('cars', 'bookings.car_id', 'cars.id')
->join('users', 'cars.user_id', 'users.id')
->join('services', 'bookings.service_id', 'services.id')
->where('bookings.start_time', '>', $now)
->where('users.id', auth()->user()->id)
->orderBy('bookings.start_time', 'ASC')
->get(['cars.plate', 'bookings.end_time', 'services.name']);
but I need it with
$bookings = auth()->user()->cars()->with('bookings.service')->get();
like: cars.plate | booking.start_time | service.name
Thanks
Please or to participate in this conversation.