基于此代码:https://devdojo.com/episode/laravel-user-image我创建了以下代码,以便上传头像并删除旧头像。我尝试使用Storage:Facade,但我不确定它是否是正确的方法。所以,让我们看看我的代码摘录:
use Illuminate\Support\Facades\Storage;
..
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
//Using Image intervention, storing to Public/Images/user
Image::make($avatar)->orientate()->fit(220)->save( public_path('/images/user/' . $filename ) );
$user = Auth::user();
$oldavatar = $user->avatar;
$user->avatar = $filename;
$user->save();
//Delete old avatar
if($oldavatar != 'profile.jpg' and Storage::disk('public')->exists('/images/user/' . $oldavatar );){
Storage::disk('public')->delete('/images/user/' . $oldavatar );
}
所以我用dd测试了它(存储::磁盘('公共') - >存在(' index.php'));我尝试了每个文件。我还在filesystem.php中添加了一个带
的磁盘 'images' => [
'driver' => 'local',
'root' => storage_path('app/public/images'),
'visibility' => 'public',
],
仍然没有,我对存在感到虚伪。
答案 0 :(得分:1)
对于未来的读者:
//e.g. user/hashMD5.jpg
$filename = $avatar->hashName('user');
$image = Image::make($avatar)->orientate()->fit(220);
$location = Storage::disk('images')->put($filename, (string) $image->encode());
if($location){
$user = Auth::user();
$oldfilename = $user->avatar;
$oldfileexists = Storage::disk('images')->exists( $oldfilename );
//Delete old avatar
if($oldfilename != 'user/profile.jpg' and $oldfileexists){
Storage::disk('images')->delete( $oldfilename );
}
//Save current image to database. Sollte ich nicht update benutzen?
$user->avatar = $filename;
$user->update();
}
使用filesystem.php:
'images' => [
'driver' => 'local',
'root' => storage_path('app/public/images'),
'visibility' => 'public',
],
答案 1 :(得分:0)
public_path()
和磁盘' public'没有相同的根。
公共磁盘可能指向:.../yoursite/storage/app/public
public_path()
会返回类似:.../yoursite/public
公共磁盘链接到.../yoursite/public/storage
- >的公用文件夹。 .../yoursite/storage/app/public