1. Go to this page and download the library: Download mannikj/laravel-sti library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mannikj / laravel-sti example snippets
Schema::table('table', function (Blueprint $table) {
$table->sti()->nullable();
});
use MannikJ\Laravel\SingleTableInheritance\Traits\SingleTableInheritance;
class Root extends Model {
use SingleTableInheritance;
}
class Sub1 extends Root {}
class Sub2 extends Root {}
use MannikJ\Laravel\SingleTableInheritance\Traits\SingleTableInheritance;
class Root extends Model {
use SingleTableInheritance;
protected $stiSubClasses = [
Sub1::class, Sub2::class
]
}
class Sub1 extends Root {
protected $stiSubClasses = [
Sub3::class
]
}
class Sub2 extends Root {}
class Sub3 extends Sub1 {}
public static function resolveTypeViaClass()
{
$type = (new \ReflectionClass(static::class))->getShortName();
$type = str_replace('Component', '', $type);
$type = strtolower($type);
return static::isSubclass()
? $type
: null;
}
public function resolveModelClassViaAttributes($attributes = [])
{
$type = $this->resolveTypeViaAttributes($attributes);
// Map class to type
$mapping = [
'motif' => MotifComponent::class,
'text' => TextComponent::class,
];
return $type
? data_get($mapping, $type)
: static::class;
}
class Animal extends Model
{
use SingleTableInheritance;
protected $fillable = ['name'];
public function resolveTypeViaAttributes($attributes = [])
{
if ($category = Category::find(Arr::get($attributes, 'category_id'))) {
return $category->config_class;
};
}
public function applyTypeCharacteristics($type)
{
$this->category_id = Category::where('config_class', $type)->first()?->id;
}
public function scopeSti(Builder $builder)
{
$builder->whereHas('category', function ($query) use ($builder) {
$query->where('categories.config_class', static::class);
});
}
public function category()
{
return $this->belongsTo(Category::class, 'category_id')->withDefault([
'config_class' => static::class
]);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.