Tricks

Link to related model from table

Jun 27, 2022
pxlrbt / Dennis Koch
Table builder

I regularly want to link the related models from the table and created a little macro for it:

Column::macro('linkRecord', function ($view = 'edit') {
return $this->url(function ($record) use ($view) {
if ($record === null) {
return null;
}
 
$selectedResource = null;
$relationship = Str::before($this->getName(), '.');
$relatedRecord = $record->{$relationship};
 
if ($relatedRecord === null) {
return null;
}
 
foreach (Filament::getResources() as $resource) {
if ($relatedRecord instanceof ($resource::getModel())) {
$selectedResource = $resource;
 
break;
}
}
 
return $selectedResource::getUrl($view, $relatedRecord->getKey());
});
});

No comments yet…