chrisgrim
3 months ago

Filtering through array data in Laravel Controller

Posted 3 months ago by chrisgrim

Hey Guys, I am stuck and no matter how much I look around the internet I can't seem to figure out my problem. I have an array of numbers [1,2,3] and I want to filter some code with each of those numbers.

//for this example I am calling this test. But in reality I would get this from ids of my model
        $test = [1,2,3];


        //This creates 30 dates into the past
        $dates = collect();

        foreach( range( -30, 0 ) AS $i ) {
            $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
            $dates->put( $date, 0);
        }

        //this selects all the dates that a redirect_id is added to redirectstatistic
        $redirects = RedirectStatistic::where('redirect_id', '=', $test)
                ->where( 'created_at', '>=', $dates->keys()->first() )
                ->groupBy( 'date' )
                ->orderBy( 'date' )
                ->get( [
                     DB::raw( 'DATE( created_at ) as date' ),
                     DB::raw( 'COUNT( * ) as "count"' )
                 ] )
                 ->pluck( 'count', 'date' );


        //this merges those redirect dates with the empty calendar created above
        $redirectCalendar = $dates->merge( $redirects );

You can see in my first where() I am filtering by each number from the array. My ultimate goal would be to have 3 30day calendars where the count only includes for each where the redirect_id is equal to 1, 2, 3.

I hope this makes sense. I am probably doing this the wrong way but I am struggling to figure it out. Thanks so any help

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