Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

muazzamazaz's avatar

Laravel pivot insert creating invalid query

using below code:

$vehicle_type = $request->vehicle_type;
$vtype =array('vehicle_type'=> $vehicle_type);
 $vehicletype = VehicleType::create($vtype);
            
            $mileage_slot = $request->input('mileage_slot', []);
            $fare = $request->input('price', []);

            for ($i=0; $i < count($mileage_slot); $i++) {
        if ($mileage_slot[$i] != '') {
            $vehicletype->vehicle_type_slots()->attach($mileage_slot[$i], ['fare' => $fare[$i]]);
            

        }

model VehicleType

 public function vehicle_type_slots()
    {
        return $this->belongsToMany(VehicleTypeSlot::class)->withPivot(['fare']);
    }

Its creating following query for detail table with wrong table name

insert into vehicle_type_vehicle_type_slot (fare, vehicle_type_id, vehicle_type_slot_id) values (?, ?, ?)"`

it should be

insert into vehicle_type_slot (fare, vehicle_type_id, mileage_slot) values (?, ?, ?)"

0 likes
6 replies
devingray_'s avatar
Level 8
public function vehicle_type_slots()
    {
        return $this->belongsToMany(VehicleTypeSlot::class, 'vehicle_type_slot')->withPivot(['fare']);
    }

Have you tried to name the relationship table?

muazzamazaz's avatar

also tell me why its adding its own column named vehicle_type_slot_id, I don't need it but want to add column mileage_slot as

protected $fillable = [
        'vehicle_type_id',
        'mileage_slot',
        'fare'
    ];
devingray_'s avatar

The ->withPivot(['fare', 'mileage_slot']); will allow that

muazzamazaz's avatar

its creating unknown column vehicle_type_slot_id which is not listed in model

devingray_'s avatar

I am not 100% sure what that is caused by, but I would suggest maybe to look at HasManyThrough relationships, you can define a pivot model and this will allow you to work directly with models

Please or to participate in this conversation.