dillingham / interacts-with-uploads
向请求对象添加上传功能
1.0.0
2021-04-15 21:59 UTC
Requires (Dev)
- orchestra/testbench: ^6.17
- phpunit/phpunit: ^9.5
README
Laravel 特性添加 FormRequest 上传
安装
composer require dillingham/interacts-with-uploads
并将以下特性添加到您的 FormRequest 类中
use \Dillingham\InteractsWithUploads;
现在您可以在控制器中调用以下方法
新的上传
$request->upload('key')
public function store(CreateProfileRequest $request) { $request->upload('banner'); $profile = Profile::create($request->validated()); return redirect()->route('profiles.show', $profile); }
存储文件并将其路径添加到 validated()
的同一键: banner
这使得 $profile->banner
等于 /uploads/asfos8asfoafaf9q3wf.jpg
更新上传
$request->upload('binding.key')
public function update(UpdateProfileRequest $request, Profile $profile) { $request->upload('profile.banner'); $profile->update($request->validated()); return redirect()->route('profiles.show', $profile); }
如果请求中有新的文件用于 key
,它将删除旧文件并上传新文件
如果没有新文件在请求中,它将原始文件路径添加回 validated()
因此,为该 key
提交 null
将导致相同的路径/对模型没有任何更改。
它将使用 key
& 路由模型绑定 获取原始文件路径,在本场景中为 profile
绑定 profile
通过 Route::
中定义的类型提示模型连接起来,并使用 {binding}
语法
手动更新
如果您不使用路由模型绑定,您可以手动设置更新路径。
public function update(UpdateProfileRequest $request, Profile $profile) { $request->updateUpload($profile, 'banner'); $profile->update($request->validated()); return redirect()->route('profiles.show', $profile); }
参数
您可以指定一些选项并覆盖默认值。
$request->upload('banner', 'uploads', 'public');
uploads
:是存储中的默认路径public
:是 config/filesystems 中的默认磁盘