Search code examples
phpmysqllaraveleloquentlaravel-5.3

Can't Display All Records In Laravel Pivot Table


I have a Players / Lessonhours pivot table that is saving all of the values passed to it from a form. In my view however, it only shows some of the records associated. It seems I am having a problem when I do a $players->lessonhour->toArray. When I do $lessonhours->players->toArray(), I only get some of the records. I can't see what I am doing wrong in the relationship setup. Something obviously needs tewaking. Can anyone help?

Tinker:

Tinker view

MySql:

MySql view

Player Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Collective\Html\Eloquent\FormAccessible;
use Carbon\Carbon;


class Players extends Model
{
    public $table = "players";

    protected $fillable = array('fname', 'lname', 'gender', 'birthdate');


    public function users()
    {
        return $this->belongsTo('App\User', 'users_id');
    }

    public function lessonhours()
    {
        return $this->belongsToMany('App\Lessonhours', 'lessonhour_player',    'lessonhours_id', 'players_id');
    }

    public function getFullName($id)
    {
        return ucfirst($this->fname ) . ' ' . ucfirst($this->lname);
    }

   protected $dates = ['birthdate'];

    public function setBirthdateAttribute($value)
    {
        $this->attributes['birthdate'] = Carbon::createFromFormat('m/d/Y',   $value);
    }
}


Lessonhours Model:

     <?php

namespace App;

use Illuminate\Database\Eloquent\Model;
 use Collective\Html\Eloquent\FormAccessible;
use Carbon\Carbon;

class Lessonhours extends Model
{
    protected $fillable = array('signup_date', 'players_id', 'packages_id');

    public $table = "lessonhours";

    public function players()
    {
        return $this->belongsToMany('App\Players', 'lessonhour_player',  'lessonhours_id', 'players_id');
    }

    public function packages()
    {
        return $this->belongsTo('App\Packages', 'packages_id');
     }

    public function hoursused()
    {
       return $this->hasMany('App\Hoursused', 'lessonhours_id');
    }

    protected $dates = ['signup_date'];

    public function setSignUpDateAttribute($value)
    {
        $this->attributes['signup_date'] = Carbon::createFromFormat('m/d/Y',     $value);
    }
}

This is what the view shows. Everyone on the list should have at least 1 package, some have 2.

Player List


Solution

  • In Players model swap lessonhours_id and players_id:

    public function lessonhours()
            {
                return $this->belongsToMany('App\Lessonhours', 'lessonhour_player', 'players_id', 'lessonhours_id');
            }