Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TechKat's avatar

Grouping records based on an ID.

Hello,

I run a micro image hosting website and collect data such as referer URLs for analytic reasons. I have a database table called referers with 2 main columns: image_id and referer_url. The image ID refers to the ID of the image in the uploads table, the referers URL refers to what was grabbed with $_SERVER['HTTP_REFERER'], so the database looks like this:

image_id        | referer_url
-----------------------------------------------------------------------------------
123         | google.com
321         | bing.com
123         | laracasts.com

and so on...

I want to create a page that lists this data, but more compact to reduce loading times. How could I go about doing this?

Here's an example how I'd like the table to look: http://kopy.io/jZ3lQ

I assume this would mean something to do with the ->groupBy() command? I am hoping this is something as simple as passing a single variable into the view() function which contains an array like:

[123] => [
'youtube.com',
'google.com'
],
[321] => [
'laracasts.com'
]
0 likes
5 replies
bestmomo's avatar

A simple groupBy :

Referer::groupBy('image_id')->get();
TechKat's avatar

@bestmomo Is there any way Eloquent can simplify this so image_ids are the array keys, and the array for those keys are the URLs? Also, that code only pulls the first result for each image ID, I want to be able to get them all.

bestmomo's avatar

Sorry, should use orderBy to get all records :

Referer::orderBy('image_id')->get();

So you can use a loop to echo your data or create an array as you want.

bestmomo's avatar
Level 52

@TechKat

There is an elegant solution :

In Referer model set this relation :

class Referer extends Model
{
    public function referers()
    {
        return $this->hasMany('App\Referer', 'image_id', 'image_id');
    }
}

Now you can write thing like that :

$referers = Referer::with('referers')->groupBy('image_id')->get();
foreach ($referers as $referer) {
    echo $referer->image_id . '<br>';
    foreach ($referer->referers as $ref) {
        echo $ref->referer_url . '<br>';
    }
};
1 like

Please or to participate in this conversation.