Search code examples
laraveleloquentlaravel-query-buildereloquent-relationship

How to get all the user data from another table and include them on user list in laravel?


I am using 2 tables upon displaying my users in my users>index.blade

these 2

USER table

enter image description here

and COLLECTOR_MEMBERS table

enter image description here

The result is this

enter image description here

Now my problem is I want to connect to the other table called

COMMISSIONS table

enter image description here

to achieve this result

enter image description here

MODELS

COMMISSIONS Model

enter image description here

USER

enter image description here

COLLECTOR MEMBER

enter image description here

USER Controller index function

public function index(Request $request)
{
    $users = User::all();           
    $admins = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'admin');
    })->get();

    $collectorList = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'collector');
    })->with('collectorList')->get();

    $borrowers = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'borrower');
    })->get();

    $userProfile = Auth::user()->id;

    if (Auth::User()->hasRole(['borrower','collector'])){
        return redirect('dashboard/profile/'.$userProfile);
    }

    return view('dashboard.users.index', compact('users','profile'))
            ->with('admins',$admins)
            ->with('borrowers',$borrowers)
            ->with('collectorList',$collectorList);
            // ->with('collectorBorrowers',$collectorBorrowers);
}

How wan I display the commission_amount column from commissions table? to make my list like this

enter image description here


Solution

  • You could use sum aggregate function, your code should look like this.

    $collectorList = User::whereHas('roles', function ($q) {
          $q->where('roles.name', '=', 'collector');
        })->with(['collectorCommission' => function($query) {
              $query->sum('commission_amount');
    }])->get();
    

    Assuming that you have this relationship in your user model

    public function collectorCommission() [
       return $this->hasMany('App\Commissions', 'user_id');
    }
    

    You cant use belongsToMany relationship since this relationship requires you an intermediary table in your second argument.

    You should use hasMany relationship considering that one user has many commissions.