Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel model tree

//Function
public function getTree()
    {
        return AttributeGroupModel::query()->with('attributes')->get()->transform(function ($group) {
            return [
                'id' => $group->id,
                'name' => AdminService::trans($group->name),
                'values' => $group->attributes->map(function ($attribute) use ($group) {
                    return [
                        'id' => $attribute->id,
                        'name' => AdminService::trans($attribute->name),
                        'group_id' => $group->id,
                    ];
                })
            ];
        });
    }

//Model

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use SpatieTranslatableHasTranslations;

class AttributeGroupModel extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = "attribute_groups";


    protected $fillable = [
        "id",
        "name",
        "sort_order"
    ];

    protected $casts = [
        'name' => 'array',
    ];

    public function attributes()
    {
        return $this->hasMany(AttributeModel::class, 'attribute_group_id', 'id');
    }

}
 
PREVIOUS NEXT
Tagged: #laravel #model #tree
ADD COMMENT
Topic
Name
6+1 =