Tuesday 18 September 2018

Laravel Filtering Eloquent Results and Left Join Example

These scripts join table demographics to countries table by looking into line 2.
Line 7 to 18 shows how can we filter the resulted collection on the results.
Finally, this returns an array of demographics with age, gender, and location as indexes.


       $mixDemographics =DB::table('demographics')
            ->leftJoin('countries', 'demographics.country_id', '=', 'countries.iso_3166_2')
            ->where('user_id',$userId)
            ->get();

        $demographics = [];
        $demographics['age'] = $mixDemographics->filter(function ($demo) {
            return ($demo->metric == 'AGE');
        });

        $demographics['gender'] = $mixDemographics->filter(function ($demo) {
            return ($demo->metric == 'GENDER');
        });


        $demographics['location'] = $mixDemographics->filter(function ($demo) {
            return ($demo->metric == 'COUNTRY');
        });

        return $demographics;



Share:

Popular Posts

Recent Posts

Pages

Powered by Blogger.

About Me

My photo
For the past 10 years, I've been playing with codes using PHP, Java, Rails. I do this for a living and love new things to learn and the challenges that comes with it. Besides programming I love spending time with friends and family and can often be found together catching the latest movie or planning a trip to someplace I've never been before.