jj15's avatar
Level 10

Guidance with relationships for a URL shortening app

Hello all,

I've been learning Laravel for about three months now and am currently working on a URL-shortening application.

I'm wanting to create a user dashboard that displays various statistics to the user about their links such as how many they have, total visits to their links, top referrer, and top country.

I have three models: User, Link, and LinkVisit (which I believe are all self-explanatory), with the following relationships:

User -> hasMany -> Link /// Link -> hasMany -> LinkVisit

I am able to get the total amount of links for a user via the first relationship but am a bit stumped on how I can get the rest of the statistics I mentioned, should I re-factor my relationships, do some sort of join, or go have a muffin?

Thanks in advance to anyone who can guide me in the right direction, I'd appreciate it :)

0 likes
3 replies
khaledw62's avatar
Level 6

No you can use hasManyThrough relation like so

class User extends Authenticatable
{
    public function linkVisits()
	{
        return $this->hasManyThrough(LinkVisit::class,Link::class);
	}

and then

	User::query()->withCount('linkVisits')->get()

Please or to participate in this conversation.