I have a laravel project with a one to one relationship. But I have a problem, I can't delete the data. The code looks perfectly normal and no errors appear, but it can't delete the data
this is my table structure
Teacher table
- id
- name
- username
- nip
Kelas table
- nama_kelas
- username
- teacher_id
Migration kelas table :
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateKelasTable extends Migration
{
public function up()
{
Schema::create('kelas', function (Blueprint $table) {
$table->id();
$table->string('nama_kelas');
$table->string('username')->unique();
$table->foreignId('teacher_id')->constrained()->cascadeOnDelete();
$table->timestamps();
});
}
}
Migration teacher table :
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTeachersTable extends Migration
{
public function up()
{
Schema::create('teachers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('username')->unique();
$table->bigInteger('nip')->unique()->nullable();
$table->timestamps();
});
}
}
Teacher Model :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function kelas()
{
return $this->hasOne(Kelas::class);
}
public function getRouteKeyName()
{
return 'username';
}
}
Kelas Model :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kelas extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function teacher()
{
return $this->belongsTo(Teacher::class);
}
public function getRouteKeyName()
{
return 'username';
}
}
Kelas Delete Controller :
public function destroy(Kelas $kelas)
{
$kelas->delete();
return redirect('/kelas');
}
Button Delete :
<form action="{{ route('kelas.destroy', $k->username) }}" method="POST" class="d-inline">
@method('DELETE')
@csrf
<button onclick="return confirm('Are you sure you want to delete this post?')">
Delete
</button>
</form>