Mercurial > packages > framework
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/Models/BaseModel.php Mon Jun 09 23:07:17 2025 -0400 @@ -0,0 +1,89 @@ +<?php + +namespace Wizard\Framework\Models; + +use Wizard\Framework\Traits\Filterable; +use Illuminate\Database\Eloquent\Model; + +class BaseModel extends Model +{ + use Filterable; + + protected $default_relations = []; + + public static function boot(): void + { + parent::boot(); + + self::creating(function ($item) { + $item->created_by = \Auth::user()?->id ?? ''; + $item->updated_by = \Auth::user()?->id ?? ''; + }); + + self::saving(function ($item) { + $item->updated_by = \Auth::user()?->id ?? ''; + }); + } + + protected static function load_auxilary_data() + { + $data = []; + + $instance = new static; + + foreach ($instance->default_relations as $relation) { + $related_model = $instance->$relation()->getRelated(); + $related_table = $related_model->getTable(); + $data[$related_table] = $related_model->all()->pluck('name', 'id')->toArray(); + } + + return $data; + } + + public static function load_index() + { + return static::load_auxilary_data(); + } + + public static function load_create() + { + return static::load_auxilary_data(); + } + + public static function load_edit() + { + return static::load_auxilary_data(); + } + + /** + * Retrieve a query builder instance with default relations loaded. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public static function data_query() + { + $query = static::query(); + + $instance = new static; + + foreach ($instance->default_relations as $relation) { + $query->with($relation); + } + + return $query; + } + + /** + * Retrieve a query builder instance with default relations loaded. + * + * @return \Illuminate\Database\Eloquent\Builder + */ + public static function get_data(array $validated = []) + { + $query = static::data_query(); + + $query->filter($validated); + + return $query->get(); + } +}
