BelongsToMany Full Name Accessor

I have
public function courses()
{
return $this->belongsToMany(Course::class);
}
public function courses()
{
return $this->belongsToMany(Course::class);
}
in Course Model have
public function getFullNameAttribute()
{
return $this->department->name . ' ' . $this->course . ' ' . __('term');
}
public function getFullNameAttribute()
{
return $this->department->name . ' ' . $this->course . ' ' . __('term');
}
When call Tables\Columns\TextColumn::make('courses.full_name') Getting empty field. How can I solve this?
14 Replies
toeknee
toeknee2mo ago
This is because we use the column names in the query, not as an accessor. do
Tables\Columns\TextColumn::make('courses.full_name')
->getStateUsing(fn($record) => $record->courses->full_name)
Tables\Columns\TextColumn::make('courses.full_name')
->getStateUsing(fn($record) => $record->courses->full_name)
Arshavir
ArshavirOP2mo ago
getting Property [full_name] does not exist on this collection instance.
toeknee
toeknee2mo ago
try $record->courses->fullName
Arshavir
ArshavirOP2mo ago
already tried with this:
Tables\Columns\TextColumn::make('courses')
->formatStateUsing(fn(Model $state) => $state->full_name)
Tables\Columns\TextColumn::make('courses')
->formatStateUsing(fn(Model $state) => $state->full_name)
fullName not resolving
LeandroFerreira
LeandroFerreira2mo ago
personally, I would create a virtual column and use courses.full_name
Arshavir
ArshavirOP2mo ago
this one working fine Also I noted if working with belongsTo then Tables\Columns\TextColumn::make('course.full_name') working virtual column much better as @Leandro Ferreira described!
LeandroFerreira
LeandroFerreira2mo ago
yes, and you can also use this with ->searchable()
Arshavir
ArshavirOP2mo ago
I use searchable with array like searchable(['name', 'surname']) Can you explain why course.full_name working, but courses.full_name not working. belongsTo vs belongsToMany
LeandroFerreira
LeandroFerreira2mo ago
I think this should work..
Arshavir
ArshavirOP2mo ago
When call Tables\Columns\TextColumn::make('courses.full_name') Getting empty field.
LeandroFerreira
LeandroFerreira2mo ago
Did you try another column?
Arshavir
ArshavirOP2mo ago
yes Tables\Columns\TextColumn::make('courses.course') working
protected $fillable = [
'department_id',
'course',
];
protected $fillable = [
'department_id',
'course',
];
public function getFullNameAttribute()
{
return $this->department->name . ' ' . $this->course . ' ' . __('term');
}
public function getFullNameAttribute()
{
return $this->department->name . ' ' . $this->course . ' ' . __('term');
}
in Subject Model
LeandroFerreira
LeandroFerreira2mo ago
I thought you were using virtual column..
Arshavir
ArshavirOP2mo ago
I don't using virtual column, because I use JSON fields for multilanguage.
Want results from more Discord servers?
Add your server