Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom pivot's mutator called when getting belongsToMany() relationship #23234

Closed
ghost opened this issue Feb 20, 2018 · 0 comments
Closed

Custom pivot's mutator called when getting belongsToMany() relationship #23234

ghost opened this issue Feb 20, 2018 · 0 comments

Comments

@ghost
Copy link

ghost commented Feb 20, 2018

  • Laravel Version: 5.5.34
  • PHP Version: 7.0.22
  • Database Driver & Version: MySQL 5.7.20

Description:

Getting or eager-loading a belongsToMany() relationship causes any defined custom pivot's mutators to be called.

Steps To Reproduce:

Create two simple models with a custom pivot that has a mutator:

class OneTable extends Model
{
    public $table = 'one_table';

    protected $guarded = [];

    public function anotherTables()
    {
        return $this->belongsToMany(AnotherTable::class, 'one_table2another_table', 'one_table_id', 'another_table_id')
            ->withPivot('data')
            ->using(OneTable2AnotherTable::class);
    }
}
class AnotherTable extends Model
{
    public $table = 'another_table';

    protected $guarded = [];
}
class OneTable2AnotherTable extends Pivot
{
    public function setDataAttribute($value)
    {
        throw new \Exception('MUTATOR CALLED');
    }
}

Get a OneTable instance and its related AnotherTables:

$oneTable = OneTable::find(1);
$oneTable->anotherTables()->get();

Or eager-load its related AnotherTables:

OneTable::with('anotherTables')->find(1);

In both cases, the OneTable2AnotherTable pivot's mutator is called and the respective exception is therefore thrown.
Note that this doesn't happen when getting a regular non-pivot model or a regular model's related models defined via hasMany().

@ghost ghost changed the title Custom pivot's mutator called when eager-loading belongsToMany() relationship Custom pivot's mutator called when getting belongsToMany() relationship Feb 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants