beartown's avatar

Clean way to cast property as collection of collections?

Let's say I have a model named Minefield, which has a property named schema, which is a two-dimensional array. This is not a real example, but I want to use something nice and simple.

I'm storing the schema as JSON and I cast it as collection:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Minefield extends Model
{
    protected function casts(): array
    {
        return [
            'schema' => 'collection',
        ];
    }
}

Now, whenever I get $minefield->schema, it returns a collection of arrays. Is there any built-in fancy way to return it as collection of collections instead? I thought about adding an accessor, but then I need to parse JSON myself and it feels suboptimal. Is there any nicer way?

0 likes
1 reply
jaseofspades88's avatar

Create a custom cast that maps over each element. What about beyond two levels? e.g. A collection of collections of collections? If it's possible, build a recursive method within said cast and then it doesn't matter how many levels. If only two, then simply map into a collection.

Please or to participate in this conversation.