Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel localrole per many to many 3 foreign

//User model
public function role() {
        //Returns local role of user in board. Get pivot user_id to connect to user then filter on board by given board_id in pivot.
		//In this case we call the object with multiple users and unique roles boards.
       return $this->belongsToMany(Role::class, 'board_user_roles', 'user_id')->wherePivot('board_id','=',$this->pivot->board_id);
    }
//Board model
//Returns all user of selected board. With the pivot role_id !! ->withPivot is needed to connect the user/board/role in the user model !!
public function users() {
        return $this->belongsToMany(User::class, 'board_user_roles')->withPivot('role_id');
    }
//board_user_roles migration
Schema::create('board_user_roles', function (Blueprint $table) {
            $table->unsignedBigInteger('board_id');
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
        });
//Example how u request the local role in board:
Board::all()->first()->users->first()->role
  // returns: 
  AppModelsRole {#4493
         id: 99,
         color_id: 2,
         name: "Admin",
         pivot: IlluminateDatabaseEloquentRelationsPivot {#4508
           user_id: 1,
           role_id: 99,
         },
       },
 
PREVIOUS NEXT
Tagged: #laravel #localrole #foreign
ADD COMMENT
Topic
Name
4+1 =