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

meglo's avatar
Level 1

how to delete all data relating to the data to be deleted?

i dont know to explain it with clearly.

but i have case like this..

i have 3 tables

first is employees = id | name

second is attendanceDate = id | date

third is attendance_employees = employees_id | attendanceDate_id

if i delete 1 data from employees . it will also delete the effect of the data in attendance_employees. So, for example, I delete employees with id 1. All records for employee id 1 in attendance_employees are also deleted. because when I delete the employee id 1, but the employee id 1 data is still in the attendance_employees table, an error will occur. how to handle it? do I need settings on my database in mysql?

can you tell me the hint key about this ?

0 likes
4 replies
automica's avatar
automica
Best Answer
Level 54

@meglo in your migration if you have set up foreign key constraints

$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');

to cascade on delete then this should also update your join table to remove records.

see

https://laravel.com/docs/8.x/migrations#foreign-key-constraints

i'm not quite sure of your error though:

All records for employee id 1 in attendance_employees are also deleted. because when I delete the employee id 1, but the employee id 1 data is still in the attendance_employees table, an error will occur. how to handle it?

as you say all records are being deleted for employee but also they aren't ??

meglo's avatar
Level 1

this is the error: if i dont delete data from the pivot table, where the data are related. but if i delete data first from the pivot table, no error occur. i think i will try your suggestion. i will hit best answer if this work. thank you information about cascade.

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (pt_demo.absensi_karyawan, CONSTRAINT detailabsens_karyawans_id_foreign FOREIGN KEY (karyawan_id) REFERENCES karyawan (id)) (SQL: delete from karyawan where id = 2)

automica's avatar

@meglo can you post the migrations for your tables so I can install locally and see?

meglo's avatar
Level 1

thank you i already use your sugesttion. its work.

Please or to participate in this conversation.