Laravel Self Recursive Relationship

  laravel, php

I am currently learning Laravel. I have a column in database called "Folder" and it has self-dependency. There might be multiple folders in a folder. I wanted to create an api with the structure shown in expected result. However, the result that I had gotten was as actual result.

Expected and Actual Result

Can someone please guide me to achieve the expected result? I don’t want to show the children as parent.

Below is my code implementation:

Model

class Folder extends Model
{
    use HasFactory;

    /**
     * The relationships that should always be loaded.
     *
     * @var array
     */
    protected $with = ['inner_folders'];

    public function inner_folders()
    {
        return $this->hasMany(self::class, 'folder_id')->with('inner_folders');
    }

    protected $fillable = [
        'user_id',
        'folder_id',
        'folder_name',
        'folder_attr',
        'image'
    ];
}

Resource Collection

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'folder_name' => $this->folder_name,
            'folder_attr' => $this->folder_attr,
            'image' => $this->image,
            'folder_id' => $this->folder_id,
            'inner_folders' => FolderResourceCollection::collection($this->whenLoaded('inner_folders'))
        ];
    }

Controller

public function index(Request $request)
    {
        $user_id = $request->input('user_id');
        return new FolderResource(Folder::where('user_id', $user_id)->get());
    }

Thanks in advance.

Source: Laravel

Leave a Reply