Issues (350)

app/Models/Leave.php (1 issue)

Severity
1
<?php
2
3
namespace App\Models;
4
5
use App\Events\LeaveCreated;
6
use App\Events\LeaveUpdated;
7
use Backpack\CRUD\app\Models\Traits\CrudTrait;
8
use Illuminate\Database\Eloquent\Model;
9
use Spatie\Activitylog\Traits\LogsActivity;
10
11
/**
12
 * @mixin IdeHelperLeave
13
 */
14
class Leave extends Model
15
{
16
    use CrudTrait;
0 ignored issues
show
The trait Backpack\CRUD\app\Models\Traits\CrudTrait requires some properties which are not provided by App\Models\Leave: $fakeColumns, $identifiableAttribute, $Type
Loading history...
17
    use LogsActivity;
18
19
    protected $guarded = ['id'];
20
21
    protected $with = ['leaveType'];
22
23
    protected static bool $logUnguarded = true;
24
25
    protected $dispatchesEvents = [
26
        'updated' => LeaveUpdated::class,
27
        'created' => LeaveCreated::class,
28
    ];
29
30
    protected static function boot()
31
    {
32
        parent::boot();
33
34
        // do not save already existing leaves
35
        static::saving(function (self $leave) {
36
            if (self::where('teacher_id', $leave->teacher_id)->where('date', $leave->date)->count() > 0) {
37
                return false;
38
            }
39
        });
40
41
        // when a leave is, we detach the events from the teacher
42
        static::saved(function (self $leave) {
43
            $events = Event::where('teacher_id', $leave->teacher_id)->whereDate('start', $leave->date)->get();
44
            foreach ($events as $event) {
45
                $event->teacher_id = null;
46
                $event->save();
47
            }
48
        });
49
    }
50
51
    public static function upcoming_leaves()
52
    {
53
        return self::limit(15)->get()->groupBy('teacher_id'); // todo return first teacher with date span
54
    }
55
56
    public function leaveType()
57
    {
58
        return $this->belongsTo(LeaveType::class, 'leave_type_id');
59
    }
60
61
    public function teacher()
62
    {
63
        return $this->belongsTo(Teacher::class);
64
    }
65
}
66