将上传的图像存储到 Laravel 数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46922100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:51:52  来源:igfitidea点击:

storing uploaded image into database laravel

phplaravelimage-uploading

提问by blastme

I am having trouble uploading my image into database, everytime I try to upload it, the data send into the database is empty but my local disk is able to store the image and I don't know what to do. I think I might have done something wrong in the controller part

我在将图像上传到数据库时遇到问题,每次尝试上传时,发送到数据库的数据为空,但我的本地磁盘能够存储图像,我不知道该怎么做。我想我可能在控制器部分做错了什么

Controller:

控制器:

public function store1(Request $request){

   $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);


   if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = $image->getClientOriginalName();
        $size = $image->getClientSize();
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $name);

        $userImage = new UserImage;
        $userImage->name = $name;
        $userImage->size = $size;
        //dd($userImage);
        $userImage->save;
}

table that I wanted to upload to:

我想上传到的表:

Schema::create('user_images', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('size');
        $table->integer('user_id');
        $table->timestamps();
});

enter image description here

在此处输入图片说明

回答by Miggy

In your posted code, you forgot setting the data for user_id. As I can see in your schema, it is not nullable so it should have a data.

在您发布的代码中,您忘记设置user_id. 正如我在您的架构中看到的那样,它不可为空,因此它应该有一个数据。

Also, can you try putting ()in your save like so :

另外,您可以尝试()像这样保存保存吗:

 $userImage->save();