SexyMF SexyMF - 27 days ago 10
PHP Question

Laravel belongsToMany not returning the related data

I have the following relationship bellow the question.

This is the data I have in the database:


ID page_id app_id
96 1 2
97 1 3
98 1 6
99 1 7


this will return the page, but NOT the related
apps


$page = App\Page::find(1)->first();
print_r($page->apps);// this has no results


this is the class maps, I have 2 combinations inside where you see "also not working":

class Page extends Model
{
protected $table = "pages";
//protected $appends = array('apps');//also not working
protected $with = array('apps');//


public function apps(){
return $this->belongsToMany('App\App','page_apps','page_id','app_id')->withPivot('page_id');

//return $this->belongsToMany('App\App','page_apps','page_id','app_id');//also not working
}

public function getAppsAttribute($value){
return $value;
}
}


class App extends Model
{
protected $table = "apps";
public $timestamps = true;
}


class PageApps extends Model
{
protected $table = "page_apps";
public $timestamps = true;
}

Answer

Remove this function, it overrides the ->apps for page

public function getAppsAttribute($value){
    return $value;
}
Comments