How to recover user data with all your services?

Viewed 29

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();
    });
}
1 Answers

In ClientResource.php

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,

        'my_services' => $this->my_services,
    ];
}

if you have resource file for service (let say ServiceResource.php), you may do like this

public function toArray($request)
{
    return [
        ....
        'my_services' => ServiceResource::collection($this->my_services),
    ];
}
Related