Mercurial > packages > framework
comparison src/Models/BaseModel.php @ 1:56d9c64d64aa
Setting up the base, still have plenty of work to be done here.
| author | luka |
|---|---|
| date | Mon, 09 Jun 2025 23:07:17 -0400 |
| parents | |
| children | b44434aaa767 |
comparison
equal
deleted
inserted
replaced
| 0:07e7262a8cce | 1:56d9c64d64aa |
|---|---|
| 1 <?php | |
| 2 | |
| 3 namespace Wizard\Framework\Models; | |
| 4 | |
| 5 use Wizard\Framework\Traits\Filterable; | |
| 6 use Illuminate\Database\Eloquent\Model; | |
| 7 | |
| 8 class BaseModel extends Model | |
| 9 { | |
| 10 use Filterable; | |
| 11 | |
| 12 protected $default_relations = []; | |
| 13 | |
| 14 public static function boot(): void | |
| 15 { | |
| 16 parent::boot(); | |
| 17 | |
| 18 self::creating(function ($item) { | |
| 19 $item->created_by = \Auth::user()?->id ?? ''; | |
| 20 $item->updated_by = \Auth::user()?->id ?? ''; | |
| 21 }); | |
| 22 | |
| 23 self::saving(function ($item) { | |
| 24 $item->updated_by = \Auth::user()?->id ?? ''; | |
| 25 }); | |
| 26 } | |
| 27 | |
| 28 protected static function load_auxilary_data() | |
| 29 { | |
| 30 $data = []; | |
| 31 | |
| 32 $instance = new static; | |
| 33 | |
| 34 foreach ($instance->default_relations as $relation) { | |
| 35 $related_model = $instance->$relation()->getRelated(); | |
| 36 $related_table = $related_model->getTable(); | |
| 37 $data[$related_table] = $related_model->all()->pluck('name', 'id')->toArray(); | |
| 38 } | |
| 39 | |
| 40 return $data; | |
| 41 } | |
| 42 | |
| 43 public static function load_index() | |
| 44 { | |
| 45 return static::load_auxilary_data(); | |
| 46 } | |
| 47 | |
| 48 public static function load_create() | |
| 49 { | |
| 50 return static::load_auxilary_data(); | |
| 51 } | |
| 52 | |
| 53 public static function load_edit() | |
| 54 { | |
| 55 return static::load_auxilary_data(); | |
| 56 } | |
| 57 | |
| 58 /** | |
| 59 * Retrieve a query builder instance with default relations loaded. | |
| 60 * | |
| 61 * @return \Illuminate\Database\Eloquent\Builder | |
| 62 */ | |
| 63 public static function data_query() | |
| 64 { | |
| 65 $query = static::query(); | |
| 66 | |
| 67 $instance = new static; | |
| 68 | |
| 69 foreach ($instance->default_relations as $relation) { | |
| 70 $query->with($relation); | |
| 71 } | |
| 72 | |
| 73 return $query; | |
| 74 } | |
| 75 | |
| 76 /** | |
| 77 * Retrieve a query builder instance with default relations loaded. | |
| 78 * | |
| 79 * @return \Illuminate\Database\Eloquent\Builder | |
| 80 */ | |
| 81 public static function get_data(array $validated = []) | |
| 82 { | |
| 83 $query = static::data_query(); | |
| 84 | |
| 85 $query->filter($validated); | |
| 86 | |
| 87 return $query->get(); | |
| 88 } | |
| 89 } |
