【问题标题】:Validated and uploaded image incorrect name saved in MySQL in Laravel 6在 Laravel 6 中保存在 MySQL 中的验证和上传的图像名称不正确
【发布时间】:2023-03-28 11:32:01
【问题描述】:

文本和照片的验证在 StorePost FormRequest 中进行。

public function rules()
    {
        return [
            'name' => 'required',
            'exerpt => 'required',
            'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ];
    }

然后是控制器部分:

public function store( StorePost $request )
    {
        $imageName = time().'.'.$request->photo->extension();  
        $request->photo->move(public_path('post-images'), $imageName);

        // may modify image name here but it's not elegant
        //$data = $request->all();
        //$data['photo'] = $imageName;

        Post::create( $request->all() );
    }

图像在 MySQL 中保存为/private/var/folders/zr/y1drl_rs0sl75rxvgkx8ntzm0000gn/T/phpUJKeEG。 如何在请求到达控制器之前设置其名称?

我不想像这里那样这样做(注释行)。

【问题讨论】:

  • 我不明白这个问题。在进入控制器逻辑之前设置名称?我想您可以在客户端进行设置,但我认为这不是您想要的。

标签: php laravel request image-uploading


【解决方案1】:

你可以使用

$imageName = time().'_'.$request->photo->extension();  
$request->photo->storeAs('public/post-images',$imageName);

$post = new Post;
//...
$post->photo = $imageName;
//...
$post->save();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2020-10-25
    • 2012-11-17
    • 2020-08-30
    • 2014-03-06
    相关资源
    最近更新 更多