New column from calculating 2 other eager columns Laravel

Solution 1:

Are you really need new column? You can do on your model;

protected $appends = ['my_calculation'];

public function getMyCalculationAttribute()
{
    return $this->past_bookings_count * $this->bookings_count;
}

you can access it like this:

$trekModel->my_calculation;

you can look official docs

Solution 2:

You could also do it via another step. Like that:

$collection = Trek::select('name')
            ->withCount('past_bookings')
            ->withCount('bookings')
            ->get();

$data = [];
foreach($collection as $item) {
    $data['past_bookings_count/bookings as new_col'] = ($item['past_bookings'] / $item['bookings_count']);
}


dd($data);

However, if this is passed on to a view, I would leave the loop and carry out the calculation in the view.

.blade.php

{{ $data['past_bookings_count'] / $data['bookings_count'] }}