Models

Creation of a model

This is an example of a model that will be linked to a table in the database, for more info always check the official Laravel documentation.

<?php

class User extends Authenticatable implements HasMedia
{
    use HasSlug;
    use HasAdvancedFilter;
    use Notifiable;
    use HasFactory;
    use InteractsWithMedia;

    public $table = 'users';

    protected $appends = [
        'title',
    ];

    protected $hidden = [
        'password',
    ];

    public $fillable = [
        'name',
        'surname',
        'email',
        'password',
    ];

    public $orderable = [
        'id',
        'name',
        'surname',
        'email',
        'password',
    ];

    public $filterable = [
        'id',
        'name',
        'surname',
        'email',
        'password',
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }

    public function getSlugOptions(): SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getUserImageAttribute()
    {
        return $this->getMedia('user_image')->toArray();
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_user');
    }
    
    public function userImage(): MorphMany
    {
        return $this->morphMany(Media::class, 'model')->where('collection_name', CollectionPathEnum::USER_IMAGE->value);
    }
}

Special attributes are used in the model: $orderable and $filtrable, these are used thanks to the trait HasAdvancedFilter. This trait allows us to run queries in the backend by easily applying sorting and searching filters thanks to the ->advancedFilter() trait method.

public $orderable = [
        'id',
        'name',
        'surname',
        'email',
        'password',
    ];

public $filterable = [
        'id',
        'name',
        'surname',
        'email',
        'password',
    ];

This is how the trait applies in queries:

$users = $users->advancedFilter();

This method also includes the basic laravel pagination, as if you were using paginate() method


In Balance the media is loaded not as simple attributes but as relations by using the eager loading, for example for the userImage attribute.

public function userImage(): MorphMany
{
    return $this->morphMany(Media::class, 'model')->where('collection_name', CollectionPathEnum::USER_IMAGE->value);
}

Most models use a slug also as a route key name. This is thanks to the HasSlug trait.

public function getRouteKeyName()
{
    return 'slug';
}

public function getSlugOptions(): SlugOptions
{
    return SlugOptions::create()
        ('name')
        ->saveSlugsTo('slug');
}

In the getSlugOptions() method we can specify at the trait which model parameter to use as a slug.

Last updated