Search code examples
laraveleloquentlaravel-collection

Property [roles] does not exist on this collection instance. in a many-to-many relationship


Hello I am learning relationship many to many I read the official documentation and use the conventions, but I can't make the relation many to many I get the error that the property does not exist.

how can I solve that?

Migrations

Schema::create('role_user', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
        $table->foreignId('role_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
        $table->timestamps();
    });
}

User

   Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Roles

 Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

Models:

User

 public function roles(){
        return $this->belongsToMany(role::class, 'role_user', 'user_id', 'role_id');
    }

Role

public function users(){
        return $this->belongsToMany(User::class, 'role_user','role_id','user_id');
    }

query:

$v = User::get();
 dd($v->roles);

Solution

  • $v = User::get(); returns a collection of users. If you get one user, for example, User::find(1) you will have access to the roles for this specific user.

    Another option is

    $users = User::with('roles')->get();
    
    foreach ($users as $user) {
        $userRoles = $user->roles;
    }