@Tray2
Thank you, I looked into view composers. I ended up creating a StatsService class with a method for each calculation I need. Since there was no overlap between views, in terms of what stats are needed I figured a view composer wouldn't make sense in my implementation. I'm simply calling the relevant StatsService methods in each controller and passing them to the views that way.
class StatsService
{
public static function totalSignatures()
{
return Signature::toBase()->count();
}
public static function totalLocationsSignatured()
{
return Signature::toBase()->distinct('location_id')->count('location_id');
}
public static function totalSubjectsSignatured()
{
return Signature::toBase()->distinct('subject_id')->count('subject_id');
}
public static function totalSignaturesForSubject($subjectId)
{
return Signature::toBase()->where('subject_id', $subjectId)->count();
}
public static function totalLocationsForSubject($subjectId)
{
return Signature::toBase()->where('subject_id', $subjectId)->distinct('location_id')->count('location_id');
}
public static function totalSignaturesForLocation($locationId)
{
return Signature::toBase()->where('location_id', $locationId)->count();
}
public static function totalSubjectsForLocation($locationId)
{
return Signature::toBase()->where('location_id', $locationId)->distinct('subject_id')->count('subject_id');
}
public static function totalSignaturesForSubjectAndLocation($subjectId, $locationId)
{
return Signature::toBase()->where('subject_id', $subjectId)->where('location_id', $locationId)->count();
}
public static function totalLocationsForSubjectAndLocation($subjectId)
{
return Signature::toBase()->where('subject_id', $subjectId)->distinct('location_id')->count('location_id');
}
}
class SubjectController extends Controller
{
public function show(Subject $subject)
{
$stats = ['totalVotesForSubject' => StatsService::totalVotesForSubject($subject->id),
'totalLocationsForSubject' => StatsService::totalLocationsForSubject($subject->id)];
return view('subjects.show', compact('subject', 'stats'));
}
}