tutoring/app/Models/LessonSection.php

52 lines
1.1 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class LessonSection extends Model
{
protected $fillable = ['module_id', 'title', 'year', 'order', 'slug'];
public function module()
{
return $this->belongsTo(Module::class);
}
public function lessons()
{
return $this->hasMany(Lesson::class)->orderBy('order');
}
public function chapters()
{
return $this->hasMany(Chapter::class)->orderBy('order');
}
public function getRouteKeyName()
{
return 'slug';
}
protected static function boot()
{
parent::boot();
static::creating(function ($section) {
if (empty($section->slug)) {
// Use title + uniqid to avoid collisions
$section->slug = Str::slug($section->title . '-' . uniqid());
}
});
static::updating(function ($section) {
if ($section->isDirty('title')) {
// When renaming, regenerate slug based on title + id
$section->slug = Str::slug($section->title . '-' . $section->id);
}
});
}
}