【问题标题】:How to upload an image using mass assignment in laravel 5.8?如何在 laravel 5.8 中使用批量分配上传图像?
【发布时间】:2019-11-22 20:23:39
【问题描述】:

我正在尝试使用批量分配。然而,在尝试这种方法时,我在上传图片时遇到了一点问题。
我在 News.php 模型中添加了可填充属性。

 protected $fillable = ['title','content','image','status'];

我尝试使用批量分配

 public function store(Request $request)
    {
        //Handle File upload
        if($request->hasFile('image'))
        {
            $filenameWithExt = $request->file('image')->getClientOriginalName();
            $filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
            $extension = $request->file('image')->getClientOriginalExtension();
            $fileNameToStore = $filename.'_'.time().'.'.$extension;
            $path = $request->file('image')->storeAs('public/news_images',$fileNameToStore);
        }else
        {
            $fileNameToStore = 'noimage.jpg';
        }


           News::create(request(['title','content','image','status']));



       return Redirect('/news');
    }

我遇到的错误

SQLSTATE[HY000]:一般错误:1364 字段“图像”没有 默认值(SQL:插入newstitlecontentstatusupdated_at, created_at) 值(你好!,你在尝试什么 to do ?, 0, 2019-07-13 08:45:46, 2019-07-13 08:45:46)) 异常 SQLSTATE [HY000]:一般错误:1364 字段“图像”没有 有一个默认值(HY000)

如果有另一种更简单的方法来使用批量分配上传图像。请推荐。

【问题讨论】:

  • 该错误是因为您的数据库中有一个图像列,但您没有通过它输入一个值。您应该将图像存储为文件名。
  • 我试过 News::create(request(['title','content',$fileNameToStore,'status']));但不工作
  • 因为 $fileNameToStore 不是请求变量。在调用它之前,您应该在 create 方法中存储您将使用的所有变量,否则它可能会变得有点混乱
  • 我尝试存储所有变量但没有存储图像 News::create(request(['title','content','image', $filenameWithExt,$filename,$extension,$fileNameToStore,$路径,'状态']));但是当检查数据库中的新闻表时>>它存储了这个路径 C:\xampp\tmp\php955F.tmp 而不是 /storage/news_images/image.jpg

标签: php mysql laravel laravel-5.8


【解决方案1】:

这是一个不完美的答案,因为它没有对图像使用质量分配。

$news = new News(request(['title', 'content', 'status']));
$news->image = $fileNameToStore;
$news->save();

要完全使用批量分配从请求中设置新图像路径,您必须修改请求的 FileBag 以某种方式包含具有新路径的“假”文件。这可能不是一个好的做法,除非绝对必要,否则我只会使用上面 sn-p 中显示的方式。

【讨论】:

    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 2020-10-03
    • 2013-06-09
    • 2019-09-05
    相关资源
    最近更新 更多