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

ruben777's avatar

cannot get property from associative table

I have three tables :

websites :
.id
.user_id

website_checkers:
.id
.website_id
.checker_id

checkers:
.id
.name

what I want is to get the checker name from websites.

I have built my controller this way :

public function getInfos() {
$websites = Website::where('user_id', Auth::user()->id)
            ->with('checkers')
            ->get();
 return response()->json(['websites'=>$websites],200);
}

here is my Website Model :

public function checkers(): HasMany
{
    return $this->hasMany(WebsiteChecker::class);
}

json response is :

websites [
		website {
				id: 1
				user_id: 1
				checkers  [
						checker {
						id: 1
						website_id: 1
						checker_id: 1
						}
				]
		}
]

I want to get the checker name based on the checker_id, like this :

websites [
		website {
				id: 1
				user_id: 1
				checkers  [
						checker {
						id: 1
						website_id: 1
						checker_id: 1
						name: checker
						}
				]
		}
]

Any help will be very appreciated !

0 likes
4 replies
ruben777's avatar

@Sergiu17 thank you for your answer but I have already been on doc ; I am having a really hard time doing the trick lol

Snapey's avatar
Snapey
Best Answer
Level 122

do you have WebsiteChecker model?

Add a relationship

public function checker()
{
    return $this->belongsTo(Checker::class)
}

then when retrieving;

$websites = Website::where('user_id', Auth::user()->id)
            ->with('checkers.checker')
            ->get();

json will be like

websites [
		website {
				id: 1
				user_id: 1
				checkers  [
						checker {
						id: 1
						website_id: 1
						checker_id: 1
						checker {
                            id: 1
                            name: checker
						}
				]
		}
]
1 like

Please or to participate in this conversation.