Search code examples
ajaxlaravelfiltereloquentredundancy

Using eloquent when filtering data without redundancy


I'm trying to filter data via Eloquent in a method that only answers to AJAX requests and then returns the view along with the filtered data. However I have a question:

First, lets take a look at my code:

public function AJAX_get_reports(Request $request)
{
    if($request->ajax())
    {
        $message = $request->get('message');
        $severity = $request->get('severity');

        if(strlen($message) > 0 && strlen($severity) > 0 )
        {
            $data = ServerReport::where('severity', '=', $severity)->where('message', '=', $message)->get();
        } elseif (strlen($message) > 0) {
            $data = ServerReport::where('message', '=', $message)->get();
        } elseif (strlen($severity) > 0) {
            $data = ServerReport::where('severity', '=', $severity)->get();
        } else {
            $data = ServerReport::all();
        }
        return Response::json(View::make('dashboard.reports.index', compact('data'))->render());

    }
}

This was the only way I was able to do it, it works but I feel like it's not the best way to do this, especially if you have more fields to filter, the code would take enormous proportions with the verifications, is there a best way to do this?

For example, building the query while making verifications and then run it at the end?

if(strlen($message) > 0)
{
    // add WHERE to query
}
if(strlen($severity) > 0)
{
    // add WHERE to query
}

// Execute query and get the results

Solution

  • In my opinion, your code could be simplified like so:

    public function AJAX_get_reports(Request $request) {
        if($request->ajax()) {
            $message = $request->get('message');
            $severity = $request->get('severity');
            $report = ServerReport::select('*'); //Initiate the variable for query container, change * to the columns that needs to be returned or just leave it
    
            if (strlen($message) > 0) {
                $report->where('message', '=', $message); //Add message filter
            }
    
            if (strlen($severity) > 0) {
                $report->where('severity', '=', $severity); //Add severity filter
            }
    
            //Add another filters if needed
    
            $data = $report->get(); //Get the data from either the filtered data or every single data without any filters
    
            return Response::json(View::make('dashboard.reports.index', compact('data'))->render());
        }
    }
    

    I have used this method for some projects in my company, and everything works just fine. Give it a shot.