【问题标题】:Insert a Json object in MongoDB from Laravel 7从 Laravel 7 在 MongoDB 中插入 Json 对象
【发布时间】:2021-05-19 15:27:42
【问题描述】:

我需要将图像上传到 Google 存储,并在 MongoDB 中使用 gcs 图像路径插入下面的 JSON 对象。

图片已成功上传到GCS,但我无法获取图片的图片url,也无法更新mongoDB中的路径。

JSON 对象格式

{

 "original": "/pictures/1620305924456-74535-605b8a97a02cf2c1",

 "thumbnail": "/pictures/1620305924456-74535-605b8a97a02cf2c1",

 "fileType": "image"

}

谁能帮我实现这个逻辑。

public function store(Request $request)
{
    request()->validate([
        'name' => 'required',
        'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        
    ]);
    
      $disk = Storage::disk('gcs');
      $imagePath = $request->file('imageUrl');
      $imageName = $imagePath->getClientOriginalName();
      $disk->put('pictures', $request->file('imageUrl'));
   
      $player->name ='test';
      $player->imageUrl = [
        'original' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
        'thumbnail' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
        'fileType'=> 'image'
      ];

    Appreciation::create($player);

    return redirect()->route('appreciation.index')
                    ->with('success','Record created successfully.');
}

提前致谢

【问题讨论】:

  • dd($player) 并检查数组中的内容。
  • 代码不适合我
  • 一一调试以至少检查您要保存的内容。如果您从控制器传递正确的数据。然后检查你的数据库参数。

标签: php laravel mongodb laravel-7


【解决方案1】:

最后我用下面的代码修复了它。

 request()->validate([
        'name' => 'required',
        'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        
    ]);

    $appreciation = new Appreciation();

   
    $appreciation->name = $request->get('name');
    $imagePath = $request->file('imageUrl');
    $imageName = $imagePath->getClientOriginalName();


   
    $disk = Storage::disk('gcs');
    $url = $disk->url('/pictures/'.$imageName);
   $disk->putFileAs('/pictures/', $request->file('imageUrl'), $imageName);

     $data = [
            'original' =>'/pictures/'.$imageName,
            'thumbnail' => '/pictures/'.$imageName,
            'fileType'=> 'image'
          ];
    $appreciation->imageUrl = $data;
  
    $appreciation->save();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2020-06-07
    • 2012-05-04
    • 2018-03-20
    • 2014-07-18
    • 2015-08-13
    相关资源
    最近更新 更多