bases on your relations, one company can have many members. From which member should this total be taken from? What is the meaning of this total field on the member model?
Sep 12, 2023
7
Level 5
Retrieve value from HasMany relationship associative array
Laravel 10, Filament V2
How should I modify my partial or controller to be able to fetch a specific value from a relationship (in this case – "total")?
Controller
$companies = Company::query()
->with(['achievements', 'members'])
->where('created_at', '!=', NULL)
->orderBy('created_at', 'desc')
->paginate();
Component (View)
<div class="badge badge-outline">{{$company->members}} members</div>
dd($company->members)
Illuminate\Database\Eloquent\Collection {#2049 ▼ // resources/views/components/company.blade.php
#items: array:1 [▼
0 => App\Models\CompanyMembers {#2035 ▼
#connection: "mysql"
#table: "company_members"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:11 [▼
"id" => 1
"company_id" => 2
"total" => 10
"members-20s" => null
"members-30s" => null
"members-40s" => null
"members-50s" => null
"members-60s" => null
"daiku" => 0
"created_at" => "2023-09-11 06:30:15"
"updated_at" => "2023-09-11 06:30:15"
]
#original: array:11 [▶]
#changes: []
#casts: []
#classCastCache: []
#attributeCastCache: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
+usesUniqueIds: false
#hidden: []
#visible: []
#fillable: array:8 [▶]
#guarded: array:1 [▶]
}
]
#escapeWhenCastingToString: false
}
Writing it as members['total'] or members[0]->total or members->total or members->attributes->total returns undefined, I'm super confused.
Any help would be much appreciated :)
Level 14
@Pawooo if you want to eager load the latest achievement, you can create a new relationship.
public function achievements(): HasMany
{
return $this->hasMany('App\Model\Achievement');
}
public function latestAchievement(): HasOne
{
return $this->hasOne('App\Model\Achievement')->latest();
}
now you can eager load the latest achievement for companies Company::query()->with(['latestAchievement'])
1 like
Please or to participate in this conversation.