Skip to content
Advertisement

Insert a Json object in MongoDB from Laravel 7

I need upload a image to Google storage and insert the below JSON object with the gcs image path in MongoDB.

The image is successfully getting uploaded in GCS, but I am not able to get the image url of the image and also not able to update the path in mongoDB.

JSON object format

{

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

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

 "fileType": "image"

}

Can anyone help me to implement the this logic.

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.');
}

Thanks in advance

Advertisement

Answer

Finally I fixed it using below code .

 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();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement