harshamv's avatar

Store only filename when uploading a file

I have the following code to upload and store the file.

$user->update([
        'display_profile' => request()->display_profile->storeAs('avatars', $name,'public')
]);

This stores the file in the display_profile as avatars/filename.jpg.

Since I have multiple versions of the files for displaying around the views I am using prefixes like follow

thumb_filename.jpg

small_filename.jpg

large_filename.jpg

I will need to do a lot of string replace to insert the prefix in place to show the right version of the images. Is there any way I can save just the filename in the database instead of the full path?

If not what's the best way to show my files in the view?

1 like
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

Why not separating the file upload with the update:

// upload the file:
request()->display_profile->storeAs('avatars', $name,'public');

// save just the filename
$user->update([
        'display_profile' => $name
]);

or getClientOriginalName() should also give you just the name of the file:

request()->display_profile->getClientOriginalName()
2 likes
ftiersch's avatar
request()->display_profile->storeAs('avatars', $name,'public');
$user->update([
        'display_profile' => $name,
]);

You can just split it up in multiple steps :) Or have you checked out something like the spatie medialibrary package?

1 like
rouge's avatar

Either just store the filename, or use eloquent accessors.

request()->display_profile->storeAs('avatars', $name, 'public');

$user->update([
        'display_profile' => $name
]);
// User model
public function getThumbAttribute()
{
    return str_replace($search, $replace, $this->display_profile);
}

// Then use like
$user->thumb;
1 like
harshamv's avatar

Damn! so silly of me. I have the filename right there! Thanks a lot.

1 like

Please or to participate in this conversation.