Reputation: 11
What is the best way to display an icon according to the file type in front end document listing? The file type can be any type.
I am planning to try this:
public function getIconAttribute() {
$extensions = [
'jpg' => 'jpeg.png',
'png' => 'png.png',
'pdf' => 'pdfdocument.png',
'doc' => 'wordicon.jpg',
];
return array_get($extensions,$this->extension,'unknown.png');
}
But I need to specify all file types manually. Is there any better way to do this in php/laravel?
Upvotes: 0
Views: 2275
Reputation: 3102
You could match filenames to extensions, and use a file lookup.
public function getIconAttribute() {
$extension = strtolower($this->extension);
$rewrite_map = array(
'jpeg' => 'jpg',
'docx' => 'doc'
);
if(isset($rewrite_map[$extension])) {
$extension = $rewrite_map[$extension];
}
if(file_exists('/path/to/icons/dir/' . $extension . '.png')) {
return $extension . '.png';
}
return 'unknown.png';
}
You'll then only need to modify this method if you start supporting another file type with ambiguity in its extension.
Upvotes: 1