8000 [5.1] Custom pivot $casts · Issue #10533 · laravel/framework · GitHub
[go: up one dir, main page]

Skip to content
[5.1] Custom pivot $casts #10533
Closed
Closed
@diogoazevedos

Description

@diogoazevedos

My project laravel version is v5.1.19.

I think this issue is related to #8972.

class Custom extends Pivot
{
    protected $casts = [
        'json' => 'array',
    ];
}

class User extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)->withPivot('json');
    }

    public function newPivot(Model $parent, array $attributes, $table, $exists)
    {
        if ($parent instanceof Product) {
            return new Custom($parent, $attributes, $table, $exists);
        }

        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

class Product extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class)->withPivot('json');
    }

    public function newPivot(Model $parent, array $attributes, $table, $exists)
    {
        if ($parent instanceof User) {
            return new Custom($parent, $attributes, $table, $exists);
        }

        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

$user = User::find(1);
$product = $user->products->first();

$json = $product->pivot->json;
# Expect array ['category' => 'sample']
# Result string {"category":"sample"}

Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    3228 Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0