maltekiefer's avatar

A mutator to get file extension

Hello,

I have a file model like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'file_path'
    ];

    protected $appends = ['extension'];

    public function getExtensionAttribute()
    {
        return \File::extension($this->filename);
    }

}

I tried to get the extensions. But the value is always empty, what I am doing wrong? This is how I store the file, maybe this is important:

$filePath = $request->file('file')->storeAs('assets', $fileName, 'local');
0 likes
3 replies
MichalOravec's avatar

Use pathinfo to get an extension.

public function getExtensionAttribute()
{
    return pathinfo($this->file_path, PATHINFO_EXTENSION);
}

By the way it's accesor and not mutator.

2 likes
CorvS's avatar

@maltekiefer You are referencing a filename property, but your $fillable array only has name and file_path. Does that column even exist?

1 like
tykus's avatar

@maltekiefer this is information you know at the time the record is saved; it should not require an expensive Filesystem operation everytime a File record is retrieved. Just add a column on the table for the extension and store that information whenever the record is saved.

1 like

Please or to participate in this conversation.