0

I want to count the number of reservation users made in admin panel using Laravel Datatables.

Reservation model

public function customer()
  {
    return $this->belongsTo(User::class, 'customer_id');
  }

User model

public function reservations()
  {
    return $this->hasMany(Reservation::class);
  }

  public function getUsersCountAttribute()
  {
    return $this->reservations()->count();
  }

Userdatatable

->editColumn('user_reservation', function(Reservation $reservation){
     return $reservation->customer->users_count;
  });

... However, - it throws an error saying:

Argument 1 passed to App\DataTables\Admin\UserDataTable::App\DataTables\Admin\{closure}() must be an instance of App\Models\Reservation, instance of App\Models\User given,

I tried following the steps mentioned in Counting total posts by a user in the blade view ... but it didn't help..

What am I missing?

Zeth
  • 2,273
  • 4
  • 43
  • 91
Tridev Shrestha
  • 447
  • 7
  • 21

1 Answers1

1

You are creating a table of users? So, I supose your callback function expects to be given a User model. And the User model has a users_count attribute that contains the number of reservations.

->editColumn('user_reservation', function(User $user) {
    return $user->users_count;
});
Jerodev
  • 32,252
  • 11
  • 87
  • 108
  • I did as you mentioned..but throws error **Exception Message:\n\nSQLSTATE[42S22]: Column not found: 1054 Unknown column 'reservations.user_id' in 'where clause' (SQL: select count(*) as aggregate from `reservations` where `reservations`.`user_id` = 54 and `reservations`.`user_id` is not null)"}** – Tridev Shrestha Jan 15 '19 at 03:50
  • I just solved it..In **User** model, I just add the foreign key `customer_id` i.e public function reservations() { return $this->hasMany(Reservation::class, 'customer_id'); } as my foreign id is not user_id...thank u @Jerodev for your time -:) – Tridev Shrestha Jan 15 '19 at 05:33