sesc360 sesc360 - 7 months ago 26
PHP Question

Accessing the "created_at" timestamp of a pivot table entry

I need the value of the

pivot_created_at
timestamp in a pivot table entry I read out.

enter image description here

Accessing the pivot table data is already done and I use Eloquent for doing so:

public function states() {
return $this->belongsToMany('App\Classes\DispatchState')->withTimestamps();
}

public function getStatesForDispatch($dispatchReference) {
$dispatch = new Dispatch();
$dispatch = $dispatch->getDispatch($dispatchReference);
$statusArray = [];
$states = $dispatch->states()->get();

foreach ($states as $status) {
$statusArray[] = $status;
}

return $statusArray;
}


But how do I get access to this
pivot_created_at
entry to read out the timestamp? I am kind of stuck at the moment.

Answer

From the Documentation. The way to access the pivot data is:

$user = User::find(1);

foreach ($user->roles as $role)
{
    echo $role->pivot->created_at;
}

So in your case it would be:

public function getStatesForDispatch($dispatchReference) {
    $dispatch = new Dispatch();
    $dispatch = $dispatch->getDispatch($dispatchReference);

    // ->all gets the internal array from the Laravel Collection
    $statusArray = $dispatch->states->all();


    foreach ($statusArray as $status) 
    {
        $createdAt = $status->pivot->created_at;
        // do something with the created_at from the pivot table
    }

    return $statusArray;
}
Comments