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
toeknee2w 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
ArshavirOP2w ago
getting Property [full_name] does not exist on this collection instance.
toeknee
toeknee2w ago
try $record->courses->fullName
Arshavir
ArshavirOP2w 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
personally, I would create a virtual column and use courses.full_name
Arshavir
ArshavirOP2w 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
yes, and you can also use this with ->searchable()
Arshavir
ArshavirOP2w 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
I think this should work..
Arshavir
ArshavirOP2w ago
When call Tables\Columns\TextColumn::make('courses.full_name') Getting empty field.
LeandroFerreira
Did you try another column?
Arshavir
ArshavirOP2w 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
I thought you were using virtual column..
Arshavir
ArshavirOP2w ago
I don't using virtual column, because I use JSON fields for multilanguage.
Want results from more Discord servers?
Add your server