I have Collection of Category.

with App\Category::all() I get:

ID | PARENT_ID | NAME | DEPTH'

1 | 0 | parent1 | 0

2 | 0 | parent2 | 0

3 | 1 | child1 | 1

4 | 2 | child2 | 1

How I can add custom atrribute (column or method results) to my collection? The result I wanna get when I write etc: $categories=Category::with('childs');

ID| PARENT_ID | NAME | DEPTH' | CHILDS

1 | 0 | parent1 | 0 | {2 | 1 | child1 | 1 | NULL}

2 | 0 | parent2 | 0 | {3 | 2 | child2 | 1 | NULL}

3 | 1 | child1 | 1 | NULL

4 | 2 | child2 | 1 | NULL

I think you get the idea. I tried use Accessors & Mutators and I successfully added attribute with data etc.

$category->childs; // value should be {12 | 10 | name1 | 1 | NULL}

but I'm stuck because I can't pass data to method with queried data and return it back. I want to use one table, later I will add left and right columns to table to have tree database, now I'm just trying a little simpler - have parent and add children to it's collection

1 Answers

1
keizah On Best Solutions

You should use model relationship to itself:

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $with = ['childs'];

    public function childs()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }
}

CategoryController.php

public function index()
{
    $categories = Category::all();

    return $categories;
}

$categories will return result as you need:

[
  {
    "id": 1,
    "parent_id": 0,
    "name": "parent1",
    "depth": 0,
    "childs": [
      {
        "id": 3,
        "parent_id": 1,
        "name": "child1",
        "depth": 0,
        "childs": []
      }
    ]
  },
  {
    "id": 2,
    "parent_id": 0,
    "name": "parent2",
    "depth": 0,
    "childs": [
      {
        "id": 4,
        "parent_id": 2,
        "name": "child2",
        "depth": 0,
        "childs": []
      }
    ]
  },
  {
    "id": 3,
    "parent_id": 1,
    "name": "child1",
    "depth": 0,
    "childs": []
  },
  {
    "id": 4,
    "parent_id": 2,
    "name": "child2",
    "depth": 0,
    "childs": []
  }
]