psychomantis101
2 years ago

Should this code be in the controller? (google charts back-end)

Posted 2 years ago by psychomantis101

I'm making an app that uses google charts. It draws the charts using data from a database meaning I have to make a json file to pass to the front end ( https://developers.google.com/chart/interactive/docs/php_example )

My code is working fine, but I'm just concerned that it should not belong in the controller. Altogether I'm drawing 3 different charts and my controller goes down to 243 lines. Here is the code I'm using to create the json file for the pie chart (I also have functions for a column chart and line chart which are more complicated). Any advice on improving the code or where to put it would be really appreciated.

public function pieData(){
        //pulling all data for the displays
        $data = Display::all();
        //finding which day the user wishes to view
        $day = $_POST['pieDay'];
        //creating an array to insert columns and rows for graph
        $table = array();
        //creating columns
        $table['cols'] = array(
            //Labels for the chart, these represent the column titles
            array('id' => '', 'label' => 'Location', 'type' => 'string'),
            array('id' => '', 'label' => 'Activations', 'type' => 'number'),
            array('id' => '', 'label' => 'link', 'type' => 'string')
        );

        $rows = array();
        //looping through $data and putting values into $rows
        foreach($data as $row){
            $temp = array();
            //Values
            $temp[] = array('v' => (string) $row['location']);
            //if user wants to view every days data
            if($day == "whole") {
                $activations = DB::table('customer_display')->where('display_id', $row->id)->count();
            }
            //if user wants to view a specific days data
            else{
                $activations = DB::table('customer_display')->where(DB::raw('DATE(created_at)'),$day)->where('display_id', $row->id)->count();
            }
            //inserting data into the temporary array
            $temp[] = array('v' => (float) $activations);
            //inserting link into temporary array
            $temp[] = array('v' => (string) 'displays/' . $row['id']);
            //pushing temporary array into $row
            $rows[] = array('c' => $temp);
        }
        //pushing rows into $table
        $table['rows'] = $rows;
        //creating a JSON table from $table
        $jsonTable = json_encode($table, true);
        //responding to ajax request
        return response($jsonTable);
    }

Please sign in or create an account to participate in this conversation.