Laravel L5.5 No access to pivot table in "Many to many" relationship

titonior

Unfortunately, I cannot successfully access a DB column in a pivot table. Besides this, the model is working well.

Model Device

public function tasks()
{
    return $this->belongsToMany('App\Task', 'xx', 'yy', 'zz')
    ->withPivot('id', 'duedate', 'interval', 'reoccurdate', 'completed', 'state')
    ->withTimestamps();
}

Model Task

public function devices()
{
    return $this->belongsToMany('App\Device', 'xx', 'yy', 'zz')
    ->withPivot('id', 'duedate', 'interval', 'reoccurdate', 'completed', 'state')
    ->withTimestamps();
}

I tried with a very simple example but failed:

dd(Task::findOrFail(1)->pivot->created_at);

Error:

"Trying to get property of non-object"

Jeffrey Westerkamp

You can only access the pivot data if the model collection is the result of a call to the relation method that is aware of that pivot data, meaning you must access devices on a Task model to find any pivot data:

$devicesForTask1 = Task::find(1)->devices;
$devicesForTask1->each(function (Device $device) {

    // Here we can use pivot, since the models were found through a
    // relation method that implements the pivot definition. each
    // model now has its own pivot property:
    Log::info($device->pivot->duedate);
    Log::info($device->pivot->interval);
    // etc...
});

This is because of what pivot data represents: additional data that comes with a relationship definition. So created_at represents a statement such as:

Task 1 belongs to - among many - Device x since created_at.

Pivot data does not tell you anything about 1 specific model in of itself.

Problem 1:

It is an impossible to determine request to do Task::find(1)->pivot, since Task might have multiple belongsToMany relations, and the expression above does not explicitly specify which relation to access.

Problem 2: Imagine that Eloquent models would have a cure for problem 1 by implementing a method called pivotFor() that would let you do something like Task::find(1)->pivotFor('devices'). Now there is still information missing, because it is not known which of the related Device models we are trying to access the pivot data for (belongsToMany queries for a Collection of many models)

To fix problem 2 our hypothetical pivotFor method should accept a second argument of type int, whose value matches the id of the target Device. But that is just theory. Instead you can try to compose the behavior you're looking for from the facilities that eloquent models, relationships and collections already provide (it's possible), and create this implementation on a higher level (a Support class / repository, for example).

The Laravel documentation provides much more information about how all this works, and it's very likely you'll find a solution there.

in short: You'll need to determine:

  • Which relation you want to use on Task
  • Which model of the collection of related you want to get back

Since this is a higher order operation - the belongsToMany simply does not return single models - you should come up with your own implementation for what you try to achieve.

P.S.

Task::find(1)->devices returns you exactly Illuminate\Database\Eloquent\Collection|App\Device[].

You tried to access created_at on the pivot object. You should add that to the withPivot call, if that column indeed exists on the pivot table:

public function devices() 
{
    return $this
        ->belongsToMany('App\Device', 'xx', 'yy', 'zz')
        ->withPivot(
            'created_at', // Only if created_at exists on the pivot table!
            'id',
            'duedate',
            'interval',
            'reoccurdate',
            'completed',
            'state'
        )
        ->withTimestamps();
}

If you actually intended to get the created_at value for a Task or Device you should access that on the respective model instances directly:

$task = Task::find(1);

Log::info('Task was created at: ' . $task->created_at);

$task->devices->each(function (Device $device) {
    Log::info(
        'Device '
        . $device->id
        . ' was created at: '
        . $device->created_at
    );
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Laravel 5 - access specific model on many to many relationship

From Dev

Laravel 5 Eloquent count many to many relationship

From Dev

Laravel 5 | Many to Many Relationship not working

From Dev

Laravel Eloquent Many to Many relationship using a pivot table

From Dev

Laravel belongsToMany inserting '0' on pivot table ids in a many to many relationship?

From Dev

Laravel - Order by pivot value in Many to Many table relationship

From Dev

Laravel Eloquent many-to-many relationship: Use explicit pivot table

From Dev

Unable to sync conditional pivot table many to many relationship laravel

From Dev

Laravel 5 Many to Many - Table name in singular

From Dev

Should eloquent's many-to-many pivot table enforce uniqueness accross the two id columns? Laravel 5

From Dev

Laravel Removing Pivot data in many to many relationship

From Dev

Laravel 5 Many to Many insert Custom Pivot Cell

From Dev

Laravel 5 - Many to many relations - Getting the pivot data

From Dev

How express the many to many relationship with single parent table in EF 5

From Dev

Building a dynamic query of a many-to-many relationship in Laravel 5

From Dev

Empty data returning from many to many relationship laravel 5

From Dev

Laravel 5 - Dedicated Query string filtering on many-to-many Relationship

From Dev

Laravel 5 polymorphic relationship with pivot table

From Dev

Eloquent many to many relationship access table column value from pivot table

From Dev

Laravel 4 - Many to Many - pivot table not updating

From Dev

Laravel Many-to-Many Pivot Table

From Dev

Laravel 4.2 Many-to-many relationship : Can't read from pivot table

From Dev

Creating one to many relationship with pivot table of many to many relationship

From Dev

Creating one to many relationship with pivot table of many to many relationship

From Dev

Laravel 5 Eloquent Many to Many 2ndary table

From Dev

Rails 5: Many-to-Many Relationship Not Working

From Dev

How to query a pivot table data in MySQL (many to many relationship)

From Dev

Laravel many to many relationship, add more objects into "pivot"?

From Dev

Laravel 5 Eloquent ORM - Many to Many through Many to Many

Related Related

  1. 1

    Laravel 5 - access specific model on many to many relationship

  2. 2

    Laravel 5 Eloquent count many to many relationship

  3. 3

    Laravel 5 | Many to Many Relationship not working

  4. 4

    Laravel Eloquent Many to Many relationship using a pivot table

  5. 5

    Laravel belongsToMany inserting '0' on pivot table ids in a many to many relationship?

  6. 6

    Laravel - Order by pivot value in Many to Many table relationship

  7. 7

    Laravel Eloquent many-to-many relationship: Use explicit pivot table

  8. 8

    Unable to sync conditional pivot table many to many relationship laravel

  9. 9

    Laravel 5 Many to Many - Table name in singular

  10. 10

    Should eloquent's many-to-many pivot table enforce uniqueness accross the two id columns? Laravel 5

  11. 11

    Laravel Removing Pivot data in many to many relationship

  12. 12

    Laravel 5 Many to Many insert Custom Pivot Cell

  13. 13

    Laravel 5 - Many to many relations - Getting the pivot data

  14. 14

    How express the many to many relationship with single parent table in EF 5

  15. 15

    Building a dynamic query of a many-to-many relationship in Laravel 5

  16. 16

    Empty data returning from many to many relationship laravel 5

  17. 17

    Laravel 5 - Dedicated Query string filtering on many-to-many Relationship

  18. 18

    Laravel 5 polymorphic relationship with pivot table

  19. 19

    Eloquent many to many relationship access table column value from pivot table

  20. 20

    Laravel 4 - Many to Many - pivot table not updating

  21. 21

    Laravel Many-to-Many Pivot Table

  22. 22

    Laravel 4.2 Many-to-many relationship : Can't read from pivot table

  23. 23

    Creating one to many relationship with pivot table of many to many relationship

  24. 24

    Creating one to many relationship with pivot table of many to many relationship

  25. 25

    Laravel 5 Eloquent Many to Many 2ndary table

  26. 26

    Rails 5: Many-to-Many Relationship Not Working

  27. 27

    How to query a pivot table data in MySQL (many to many relationship)

  28. 28

    Laravel many to many relationship, add more objects into "pivot"?

  29. 29

    Laravel 5 Eloquent ORM - Many to Many through Many to Many

HotTag

Archive