A simple groupBy :
Referer::groupBy('image_id')->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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'
]
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>';
}
};
Please or to participate in this conversation.