stalwart1014
stalwart1014

Reputation: 471

Refactoring multiple same queries with different value

Is there a better way to refactor this code? It's basically the same line with different values. I thought of doing a for loop but maybe there's another way.

$date = $request->date;
$underConsideration = Application::whereDate('created_at',$date)->where('status','Under consideration')->count();
$phoneScreened = Application::whereDate('created_at',$date)->where('status','Phone screened')->count();
$interviewed = Application::whereDate('created_at',$date)->where('status','Interviewed')->count();
$offerExtended = Application::whereDate('created_at',$date)->where('status','Offer extended')->count();

Upvotes: 0

Views: 89

Answers (2)

kapitan
kapitan

Reputation: 2222

You should create a separate method for this.

public function myMethod()
{
   $under_consideration = $this->fetchApplicationData($request, 'Under consideration');
   $phone_screened      = $this->fetchApplicationData($request, 'Phone screened');
   $interviewed         = $this->fetchApplicationData($request, 'Interviewed');
   $offer_extended      = $this->fetchApplicationData($request, 'Offer extended');
}

private function fetchApplicationData($request, $status)
{
   return Application::
      whereDate('created_at', $request->date)
    ->where('status', $status)
    ->count();
}

That is a much cleaner code.

However, I advise that you should put the items:

Under consideration, Phone screened, Interviewed, Offer extended

into a separate table on the database and just save the status_id on your main table.

One of the major advantage on this is the speed. For example, your client wants to know all record that has a status of Interviewed for a certain date span. Database searching against integer is a lot faster than string.

Upvotes: 2

Andrew
Andrew

Reputation: 1833

You could create a method to handle the select operations. Something like:

public function yourExisitingMethod() {
    $date = $request->date;
    $underConsideration = getData($date,'Under consideration');
    $phoneScreened = getData($date,'Phone screened');
    $interviewed = getData($date,'Interviewed');
    $offerExtended = getData($date,'Offer extended');
}

public function getData($date, $status) {

    $data = Application::whereDate('created_at',$date)->where('status',$status)->count();
    
    return $data;

}

This would at the very least improve the maintainability of your code, and in my opinion improves reusability and readability.

Upvotes: 1

Related Questions