I am working on a Laravel 5.1 website where I am counting the average rent of apartments in a specific area. Besides of that I want to get the average rent by amount of rooms in the apartment. The functionality itself isn't anything that hard, but then I want to be able to get the average rent for apartments with e.g. two rooms by a variable.
How would you be able to do this in a cleaner way? I am going to have attributes for up to about 10 rooms, that would mean 20 new methods. Have to be a better way to do this?
public function average_rent($rooms, $timespan = '6 months', $fromDate = null)
{
if ($fromDate === null) $fromDate = date('Y-m-d');
$query = DB::select(
"SELECT COUNT(id) as amt, SUM(rent) AS total_rent
FROM " . env('DB_PREFIX', '') . "apartments
WHERE
rooms = " . $rooms . " AND rent > 0 AND
formatted_address LIKE '% " . $this->query_params . ", Sverige%' AND
created_at BETWEEN '" . date('Y-m-d', strtotime('-' . $timespan)) . "' AND '" . $fromDate . "'");
$avgRent = null;
$avgAmount = $query[0]->amt;
if ($avgAmount >= 10) $avgRent = round($query[0]->total_rent / $avgAmount, 0) . ' kr';
return [$avgRent, $avgAmount];
}
public function getOneRoomAvgRentAttribute()
{
return $this->average_rent(1)[0];
}
public function getTwoRoomAvgRentAttribute()
{
return $this->average_rent(2)[0];
}
public function getOneRoomAmtAttribute()
{
return $this->average_rent(1)[1];
}
public function getTwoRoomAmtAttribute()
{
return $this->average_rent(2)[1];
}