Abdo Abo
Abdo Abo

Reputation: 93

Laravel: display multi data in one row for every user

How I can display multi data in one row with foreign key by id user for example: I have users with multi ticket, i need to display for every user number of his tickets in one column.

enter image description here

this my controller

public function followticket()
{
    $data = DB::table('tickets')
        ->join('users', 'users.id', '=', 'tickets.user_id')
        ->select('users.*', 'tickets.*')->get();

    return view('Admin.suivi-tickest',compact('data'));
}

Upvotes: 0

Views: 2113

Answers (1)

rkj
rkj

Reputation: 8307

You can try with laravel model relationship

User model

public function tickets(){
  return $this->hasMany('App\Ticket', 'user_id');
}

Controller

public function followticket()
{
    $users = User::withCount('tickets')->get();
    return view('Admin.suivi-tickest',compact('users'));
}

OR

If using query builder then you can try like this

$users = DB::table('users')
            ->join('tickets', 'users.id', '=', 'tickets.user_id')
            ->select('users.*', DB::raw('count(*) as tickets_count'))
            ->groupBy('id')
            ->get();

Template

@foreach($users as $user)
   {{$user->id}} {{$user->email}} {{$user->tickets_count}}
@endforeach

Upvotes: 1

Related Questions