user860511
user860511

Reputation:

Laravel - Access additional column data within a pivot table

I have an additional column in a pivot table, and I need to access it.

Schema:

Schema::create('alert_criteria', function(Blueprint $table)
{
    $table->increments('id');
    $table->integer('alert_id')->unsigned()->index();
    $table->foreign('alert_id')->references('id')->on('alerts')->onDelete('cascade');
    $table->integer('criteria_id')->unsigned()->index();
    $table->foreign('criteria_id')->references('id')->on('criterias')->onDelete('cascade');
    $table->integer('viewed');
    $table->timestamps();
});

Criteria Modal

public function alerts()
{
    return $this->belongsToMany('Alert')->withPivot('viewed')->withTimestamps();
}

Controller

public function getMatches()
{
    $matches = Criteria::find(Auth::user()->id)
    ->alerts()
    ->get();
}

View:

  @foreach($matches as $match)
    <td>{{$match->viewed}}</td>
  @endforeach

The view doesn't return an error but it just doesn't show anything. The 'viewed' column is just 1 or 0.

Many thanks in advance.

Upvotes: 1

Views: 1383

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

To access additional pivot table columns add this to your relationship declaration:

public function alerts(){
    return $this->belongsToMany('Alert')->withPivot('viewed');
}

To then access it you have to use the pivot property

@foreach($matches as $match)
    <td>{{$match->pivot->viewed}}</td>
@endforeach

Reference

Upvotes: 5

Related Questions