Search code examples
many-to-manylaravel-5

Retrieving data from linking table (Many to Many). Laravel


Im trying to get data from my linking table sfees it is made up of student_id from students table and mfee_id from M_fees table. My models are:

Student:
class student extends Model
{
    //
    protected $fillable = ['first_name','middle_name','last_name','address','contact','dob','grade_id','status','scholorship','admission_year','passout_year'];

    public function grade() {
    return $this->belongsTo(Grade::class);
  }

  public function M_Fees() {
    return $this->belongsToMany('App\M_Fees');
  }
}

M_fees:

class M_fees extends Model
{
     protected $fillable = ['fee_type','amount'];

     public function Student()
{
     return $this->belongsToMany('App\Student');
}
}

My table structure of sfees look like: Table sfees

Now, how can i retrieve M_fees 'fee_type and amount) of particular student? I have used following in my controller:

$student=Student::all()->whereLoose('id',$sid);
foreach ($student->M_fees as $M_fees) {
    echo $M_fees->pivot->fee_type;
}

But it doesn't seem to be working.

Can anyone help me?


Solution

  • Brother try this.Sometimes you need to define the pivot table name.Hope will help.Let me know plz.

    Student:

    class student extends Model
    {
        protected $table = "table_name";
        protected $fillable = ['first_name','middle_name','last_name','address','contact','dob','grade_id','status','scholorship','admission_year','passout_year'];
    
        public function grade() {
        return $this->belongsTo(Grade::class);
      }
    
      public function M_Fees() {
        return $this->belongsToMany('App\M_Fees','sfees');
      }
    }
    

    M_fees

    class M_fees extends Model
    {
         protected $table = "table_name";
         protected $fillable = ['fee_type','amount'];
    
         public function Student()
    {
         return $this->belongsToMany('App\Student','sfees');
    }
    }
    

    Brother I think your looping has a problem.You have to loop through the student and for each student you have to fetch fee,amount.try this one.

    Brother I think your looping has a problem.You have to loop through the student and for each student you have to fetch fee,amount.try this one.

    foreach ($student as $single_student) {
    
    foreach ($single_student->M_fees as $M_fees) {
    
        echo $M_fees->pivot->fee_type;
    }
    }
    

    hope it will work.let me know