I guess you want to query the related model?
<?php
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Route;
class Car extends Model
{
public function bookings()
{
return $this->belongsToMany(Booking::class, 'booking_car');
}
}
class Booking extends Model
{
public function cars()
{
return $this->belongsToMany(Car::class, 'booking_car');
}
}
Route::get('/', function () {
$criteria = [
'fomDate' => now()->addDay(),
'toDate' => now()->addDays(3),
];
$cars = Car::query()
->whereDoesntHave('bookings', function (Builder $builder) use ($criteria) {
$builder->where('pick_up_date', '<', $criteria['fromDate']);
$builder->where('drop_off_date', '>', $criteria['toDate']);
})
->get();
return $cars;
});
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence