Skip to content

Instantly share code, notes, and snippets.

@syofyanzuhad
Created July 21, 2022 11:54
Show Gist options
  • Select an option

  • Save syofyanzuhad/a2ef8b43dc25b48f8d225bca73cd45c7 to your computer and use it in GitHub Desktop.

Select an option

Save syofyanzuhad/a2ef8b43dc25b48f8d225bca73cd45c7 to your computer and use it in GitHub Desktop.

Revisions

  1. syofyanzuhad created this gist Jul 21, 2022.
    61 changes: 61 additions & 0 deletions Karyawan.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use Spatie\MediaLibrary\HasMedia;
    use Spatie\MediaLibrary\InteractsWithMedia;

    class Karyawan extends Model implements HasMedia
    {
    use HasFactory, InteractsWithMedia;

    protected $table = 'karyawan';

    protected $fillable = [
    'user_id',
    'nip',
    'nama',
    'nik',
    'foto',
    'jenis_kelamin',
    'tempat_lahir',
    'tanggal_lahir',
    'alamat_domisili',
    'alamat_ktp',
    'no_hp',
    'bidang_id',
    'jabatan_id',
    'agama_id',
    'pendidikan_terakhir_id',
    'status_karyawan_id',
    'tanggal_masuk',
    'tanggal_keluar',
    'bank_id',
    'no_rekening',
    ];

    public function setNipAttribute()
    {
    // year join + birth date + 4 digit last karyawan id with zero padding

    $year = date('Y', strtotime($this->tanggal_masuk));
    $birth_date = date('Ymd', strtotime($this->tanggal_lahir));
    $gender = $this->attributes['jenis_kelamin']=='L' ? 1 : 2;
    $last_karyawan_id = Karyawan::count()+1;
    $increment = str_pad($last_karyawan_id, 4, '0', STR_PAD_LEFT);

    $this->attributes['nip'] = $year . $birth_date . $gender . $increment;
    }

    // boot function to set default value for setting nip attribute
    protected static function boot()
    {
    parent::boot();

    static::creating(function ($model) {
    $model->setNipAttribute();
    });
    }
    }