Custom query in EditRecord

Hi guys, How to custom the query in EditRecord? I want to count the relastionship My code:
Section::make()
->schema([
Placeholder::make('courses_count')
->label(__('Total Courses'))
->content(fn (CourseCategory $record): ?string => $record->courses_count),
Placeholder::make('created_at')
->label('Created at')
->content(fn (CourseCategory $record): ?string => $record->created_at?->diffForHumans()),

Placeholder::make('updated_at')
->label('Last modified at')
->content(fn (CourseCategory $record): ?string => $record->updated_at?->diffForHumans()),
])
->columnSpan(['lg' => 1])
->hidden(fn (?CourseCategory $record) => $record === null),
Section::make()
->schema([
Placeholder::make('courses_count')
->label(__('Total Courses'))
->content(fn (CourseCategory $record): ?string => $record->courses_count),
Placeholder::make('created_at')
->label('Created at')
->content(fn (CourseCategory $record): ?string => $record->created_at?->diffForHumans()),

Placeholder::make('updated_at')
->label('Last modified at')
->content(fn (CourseCategory $record): ?string => $record->updated_at?->diffForHumans()),
])
->columnSpan(['lg' => 1])
->hidden(fn (?CourseCategory $record) => $record === null),
8 Replies
BlackShadow
BlackShadow15mo ago
If you only want to only show it on the edit page you can use
->visible(fn($livewire) => $livewire instanceof Pages\EditRecord) // What ever page
->visible(fn($livewire) => $livewire instanceof Pages\EditRecord) // What ever page
ngoquocdat
ngoquocdatOP15mo ago
I mean i want to custom the query of current record to count the relationship. Currently $record->courses_count doesn't exists on $record because I haven't chain ->withCount('courses') to the query
BlackShadow
BlackShadow15mo ago
try: $record->courses->count()
ngoquocdat
ngoquocdatOP15mo ago
Hmm, (if it works) it will cause n+1 issue
BlackShadow
BlackShadow15mo ago
Well... maybe customize the query:
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->withCount('courses')
}
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->withCount('courses')
}
ngoquocdat
ngoquocdatOP15mo ago
cool, thanks, I thought so before, but I didn't expect getEloquentQuery it work in EditRecord too.
BlackShadow
BlackShadow15mo ago
If you right click my solution and go to apps you can mark it as resolved. @ngoquocdat
Want results from more Discord servers?
Add your server