66 lines
1.7 KiB
PHP

<?php
namespace App\Filament\Resources\StudentResource\Pages;
use App\Filament\Resources\StudentResource;
use App\Models\User;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
use Spatie\Permission\Models\Role;
class EditStudent extends EditRecord
{
protected static string $resource = StudentResource::class;
public function getTitle(): string
{
return 'Edit Siswa';
}
protected function mutateFormDataBeforeSave(array $data): array
{
$parentRole = Role::where('name', 'parent')->first();
$birthDate = Carbon::parse($data['birth_date']);
$password = $birthDate->format('dmY') . $data['nis'];
$user = User::where('email', $data['email'])->first();
$dataSubmit = [
'name' => $data['parent_name'],
'phone' => $data['parent_phone'],
];
if (!$user) {
$dataSubmit['password'] = bcrypt($password);
}
$parentUser = User::updateOrCreate(
['email' => $data['email']],
$dataSubmit,
);
// Pastikan user memiliki role parent
if (!$parentUser->hasRole('parent')) {
$parentUser->assignRole($parentRole);
}
return $data;
}
protected function getHeaderActions(): array
{
return [
Actions\DeleteAction::make()
->before(function (Actions\DeleteAction $action) {
$student = $this->record;
if ($student->email) {
User::where('email', $student->email)->delete();
}
}),
];
}
}