Search code examples
laravelmany-to-manylaravel-5.5

Laravel many to many relation not working


I'm trying to fetch data from a relationship but only relationship properties are returned.

User Model

class User extends Authenticatable { 
      use SoftDeletes; use Notifiable; 

       /** 
        * The attributes that are mass assignable. 
        * 
        * @var array 
        */ 
        protected $fillable = [ 'name', 'email', ]; 

       /* 
        * The attributes that should be hidden for arrays. 
        * 
        * @var array 
        */ 
       protected $hidden = [ 'password', 'remember_token' ]; 

       /* 
        * Get the images for the store. 
        */ 
        public function stores() { 
            return $this->belongsToMany('App\Store', 'store_user'); 
        }
}

Stores Model

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

Pivot Table

public function up() {
    Schema::dropIfExists('store_user');
    Schema::create('store_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('store_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

Existing relations between pivot table and ids are accurate.

Retrieving relations

$user = Auth::user();
$userStores = $user->stores;
$storesID = [];
foreach ($userStores as $store) {
    $storesID[] = $store->id;
}
$builder->whereIn('store_id', $storesID);

This returns:

Undefined property: App\User::$stores

I tried

$userStores = $user->stores()->get();

but that freezes the page until it throws a request took more than 60 seconds error.

Do you have any idea what I'm doing wrong?


Solution

  • The problem is 100% inside of your OwnerScope file, you should review that file first and then review the line where you assigned $builder it's value, I can't be of more help because you didn't include code from either so it's all we can do until you update your question and include both.