Search code examples
laravellumen

Remove Nulls From Query Builder Laravel


Im having a little trouble with some return data that I'm getting when running a Query Builder then paginating the data

I was wondering if anyone knew how I could remove Null Results before I paginate the data.

    // So Before I hit this
    $return = $tld->paginate($request->get('limit'))->toArray();

This is the issue after I paginate

array:12 [
  "current_page" => 1
  "data" => array:12 [
    0 => null
    1 => array:3 [

I need to get rid of those Null values, I know how to do it after I paginate however I want to get rid of them before I paginate...

Im hoping that some of you laravel Gods can help me ..

Added this extra logic for $tld

private function newest(Request $request)
{
    $this->validate($request, [
        'timescale' => [
            'required',
            Rule::in(['today', 'this_week', 'this_month', 'all_time'])
        ]
    ]);

    $tld = TimelineItem::where('timeline_items.created_at', '>', $this->timescaleToHours($request->get('timescale')));

    if ($request->search_content) {
        $tld = $this->searchContent($tld, $request->search_content, 0.4);
    } else {
        $tld = $tld->orderBy('timeline_items.created_at', 'DESC');
    }

    if ($request->types) {
        $tld = $this->filters($tld, $request->types);
    }

    if ($request->tags) {
        $tld = $this->tags($tld, $request->tags);
    }

    return $tld;
}

Solution

  • You can use filter() to remove null. Laravel Collection filter()

    $response = $tld->paginate($request->get('limit'))->toArray();
    $response['data'] = collect($response['data'])->filter()->toArray();
    return $response;