check the documentation how many to many relationships work: https://laravel.com/docs/9.x/eloquent-relationships#many-to-many
May 7, 2022
4
Level 1
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 !
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.