mfahim akbar mfahim akbar - 25 days ago 10
PHP Question

access laraval 5.2 many to many pivot . but it returns null

Hi i am trying to access the middle table attributes of many to many relationships using pivot but it return nulls.

class User extends Modal
{


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


Class Package extend Model

{

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


}


$package->pivot->created_at


but it returns null.

although i have a package associated to user.

Answer

Make sure you have timestamps in your table.

    Schema::table('user_package', function (Blueprint $table) {
        $table->timestamps();
    });

you can do this by adding in your migrations

  class User extends Modal
{


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


 Class Package extend Model
     {

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


}

if you dont add this line your timestamps will not be saved in database.

return $this->belongsToMany('App\User')->withTimestamps();

Hope this helps.