【发布时间】:2021-09-11 02:49:27
【问题描述】:
我正在创建关于向用户上传头像的逻辑:
blade.php
<image src="{{ $user->profile->image ? storage_path() . '/ app/public/' . $user->profile->image : '' }}"/>
<input type="file" id="avatar" name="avatar" style="display:none;"/>
<label for="avatar">{{ __('text.select_file') }}</label>
控制器(更新方法):
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'name' => 'required',
]);
if (request('avatar')) {
$imagePath = request('avatar')->store('uploads/avatars', 'public');
$image = Image::make(storage_path("app/public/{$imagePath}"))->fit(800, 800);
$image->save();
$imageArray = ['image' => $imagePath];
}
auth()->user()->profile->update(array_merge(
$data,
$imageArray ?? []
));
return redirect("/profile/{$user->id}");
}
当我上传图片时,它存储在 storage/app/public/uploads/avatars 中,头像的 DB 值为 uploads/avatars/name.jpeg
如您所见,我在控制器和视图文件中有硬代码app/public/,这是默认情况下,我没有更改任何路径,这里是 filesystem.php:
<?php
return [
'default' => env('FILESYSTEM_DRIVER', 'local'),
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
],
],
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
那么我该如何避免这些编码路径呢?为什么 Laravel 默认存储文件夹在 storage 而不是 public 目录?我应该将头像上传到公共目录还是将它们留在存储中?我正在寻找最佳和正确的做法?
【问题讨论】: