The problem is this : One user can subscribe to many services and one service can have many users. I have already created an intermediate table that receives the user id and the service id that is working fine, now how to return a user with all its services joined in the user resource.
here is my user model :
// relantionships
public function account_status() {
return $this -> hasMany(AccountStatus::class, 'user_id');
}
public function my_services() {
return $this -> belongsToMany(CountService::class, 'account_service_user', 'user_id', 'account_service_id');
}
here is my controller function that returns all users: :
public function index()
{
//$user = User::all();
//$user -> load('my_services');
$user = User::with('my_services') -> get();
return $this->sendResponse(ClientResource::collection($user), 'Client retrieved with successfull');
}
here is my service model :
public function services () {
return $this -> belongsTo(Service::class, 'service_id');
}
public function users() {
return $this -> belongsToMany(User::class, 'account_service_user', 'account_service_id', 'user_id');
}
my intermediate table :
public function up()
{
Schema::create('account_service_user', function (Blueprint $table) {
$table->id();
$table -> integer('user_id') -> unsigned();
$table -> integer('account_service_id') -> unsigned();
$table -> foreign('user_id') -> references('id') -> on('users') -> onDelete('cascade');
$table -> foreign('account_service_id') -> references('id') -> on('countService') -> onDelete('cascade');
$table->timestamps();
});
}