How to Upload files with Cloud Storage on Web - Firebase #19

In this chapter, we will learn how to upload an image to the Firebase Storage from the Laravel PHP project using the kreait/laravel-firebase package.

First of all you have to visit the Storage tab in the Firebase. And click on the "Get Started".



Then on click of get started, you will find two options to setup the rules and the location. For now keep the rules as it is. By default, rules would be allowed all reads and writes from authenticated users. You can learn more for making it more secure, but its not generally required.



Now the free Blaze plan does not allow the location change. It will default to us-central.



After successful setup, you would land to the root folder. This is similar to any folder structure. You can create any n level folders.



We have created the Student folder and will upload student images with Firebase doc id of Student collection document id



Following is the code to upload image to Firebase. Here we first make for image of Formdata. We would temporary upload to local public folder of your laravel project and after uploading to firebase we delete that image

 $image = $request->file('image'); //image file from frontend  
 $student   = app('firebase.firestore')->database()->collection('Student')->document('defT5uT7SDu9K5RFtIdl');  
 $firebase_storage_path = 'Students/';  
 $name     = $student->id();  
 $localfolder = public_path('firebase-temp-uploads') .'/';  
 $extension = $image->getClientOriginalExtension();  
 $file      = $name. '.' . $extension;  
 if ($image->move($localfolder, $file)) {  
     $uploadedfile = fopen($localfolder.$file, 'r');  
     app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $name]);  
     //will remove from local laravel folder  
     unlink($localfolder . $file);  
     echo 'success';  
 } else {  
     echo 'error';  
 }  

Done your image gets upload



Now below code is those who use base64 string image instead of formdata image.

 $image = $request->image; //base64 string from frontend  
 $student   = app('firebase.firestore')->database()->collection('Student')->document('defT5uT7SDu9K5RFtIdl');  
 $firebase_storage_path = 'Students/';  
 $name     = $student->id();  
 $localfolder = public_path('firebase-temp-uploads') .'/';  
 if (!file_exists($localfolder)) {  
     mkdir($localfolder, 0777, true);  
 }  
 $parts = explode(";base64,", $image);  
 $type_aux = explode("image/", $parts[0]);  
 $type = $aux[1];  
 $base64 = base64_decode($parts[1]);  
 $file = $name . '.png';  
 if (file_put_contents($localfolder . $file, $base64)) {  
     $uploadedfile = fopen($localfolder . $file, 'r');  
     app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $name]);  
     //will remove from local laravel folder  
     unlink($localfolder . $file);  
     echo 'success';  
 } else {  
     echo 'error';  
 }  

Hope image upload is clear to all of the readers. In future chapters, we will show how to fetch image from the storage and delete an image from the storage. Till then stay tuned with us. If you find this blog helpful, just share this url in social medias. Thanks for reading. Let us know your doubts in comment section and also know us if you want a specific chapter on a topic of Laravel or Firebase.

Post a Comment

38 Comments

  1. Replies
    1. hello, how to connect this storage to our firebase clound (database) ?. when we uploading to storage but it didnt save at database. thanks!

      Delete
    2. Hi Goldi,

      Thanks for reaching out us.

      As soon as image is uploaded in storage, you can store, the relative part of image. In our case, /Students/id.png in a field name image in student.

      And while fetching, you can use this field. Read Chapter 20: https://laravelwithfirebase.blogspot.com/2020/08/chapter-20-fetch-delete-image-from-firebase-storage-using-laravel-php.html

      Hope, the answer was related to what was asked.

      Please follow us and share our blog in your social media..it helps us.

      Delete
    3. Hi.

      Please read our chapters from beginning.

      Read Chapter 3, how to download Json file

      https://laravelwithfirebase.blogspot.com/2020/02/chapter-3-creating-project-in-firebase-for-laravel-php.html

      Then read chapter 5, how to place that file in laravel folder.
      https://laravelwithfirebase.blogspot.com/2020/02/chapter-5-integrate-laravel-with-google-firebase-connecting-cloud-firestore.html


      Hope it helps.

      Delete
  2. the image type i get is application/octet-stream

    ReplyDelete
    Replies
    1. Hi, Can u please share more details. We can help you in that direction.

      Thanks. Please share and follow us.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Thanks for reaching. Can you please elaborate your issue.

      Delete
  4. app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $name]);

    why here the variable is entered $ name .. but in cloud storage there is an .png extension?

    ReplyDelete
    Replies
    1. Hi Rexsy Oktiana

      Thanks for reaching out us.

      Yes there is some change, in both cases.

      //Old
      app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $name]);

      //Updated
      app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $file]);

      Hope it helps. Show your support to this blog by following us.

      Delete
    2. thank you for your response. but I got a new problem. how to make an access token on the uploaded file? so it can be accessed via a link.

      Delete
    3. Hi Rexsy Oktiana

      For your query
      If I upload without an extension, only one file is uploaded, but if I upload with an extension, the file is uploaded 2 times with an additional name _500x500 before the extension.


      Yes the Firebase extensions named Resize Images
      https://firebase.google.com/products/extensions/storage-resize-images
      will create a resized image near it samename_500x500.extension . You can add upto 3 sized for this Resize image extension.

      Hope it helps. Show your support to this blog by following us.

      Delete
    4. Hi Rexsy Oktiana

      For your query
      how to make an access token on the uploaded file? so it can be accessed via a link.


      Read the next chapter
      Chapter 20 - How to fetch and delete an image from Firebase Storage using Laravel PHP project
      https://laravelwithfirebase.blogspot.com/2020/08/chapter-20-fetch-delete-image-from-firebase-storage-using-laravel-php.html

      This provides a url for direct access.

      Hope it helps. Show your support to this blog by following us.

      Delete
    5. thanks sir.. I have read the next chapter that you recommend. but what I mean is not like that. The link that I want is like ?alt = media & token=xxx-xxxxx-xxxx-xxxxx and the link in chapter 20 is ?GoogleAccessId=XXXXXX & Expires=1596312000&Signature=XXXXXXX. I can do it manually via firebase cloud storage. if you click on a file in cloud storage, look on the right panel there is information on the location of the file. then there is a link to create a new access token.
      can this be done automatically when uploading to cloud storage?

      Delete
    6. Hi Rexsy,

      We are trying to find solution.

      getdownloadurl method is present in javascript sdk. But there is no such method in PHP sdk.

      There is lot of variables in response of uploading a object. Like self link and mediaLink. But when we call that url, not found.

      If you find the solution. Please let us know here.

      Please follow us to get notified.

      Delete
    7. how do i use javascript sdk to get the url?

      Delete
    8. hi Rexsy Oktiana

      Solution for "How to get URL from Firebase Storage getDownloadURL using Javascript SDK"

      var storage = firebase.storage();
      var pathReference = storage.ref('Students/defT5uT7SDu9K5RFtIdl.png');
      console.log(pathReference);
      pathReference.getDownloadURL().then(function(url) {
      console.log(url);
      })

      This url will give alt=media and token=XXXX, the same way you get from Firebase storage console when you click on image link.

      Done. Hope it helps. You can show your support to this blog, by just hitting the follow button on right top. And you can just give a try to our app (play store link below in green button) and provide feedback.

      Delete
    9. https://stackoverflow.com/questions/46696945/how-to-get-download-url-of-image-from-firebase-storage-php

      maybe this article will solve your problem. Make a format manual:
      https://firebasestorage.googleapis.com/b/[YOUR_BUCKET]/v0/o/[PERCENT_ENCODED_PATH_TO_FILE]?alt=media

      Delete
    10. Thanks RabbitCode, we will surely look at the solution. We think it will work. By the way, sorry for late reply, we were quite busy. Please rabbit code, you can follow us. It really helps us to see support from you.

      Delete
  5. Replies
    1. for base64 string

      even if i try normal image format , it successfully store in firebase storage but does not display in firebase storage ( goes on endless buffer )

      :( :(

      Delete
    2. hi suhasrkms

      by seeing this error "Undefined variable $aux". it seems your code having this error. Its not package error. please check once.

      Delete
  6. //Updated
    app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $file]);

    O upload ocorre, mas image não carrega no storage, fica somente um load como se a imagem estivesse quebrada.

    ReplyDelete
    Replies
    1. Hi John Mayk
      Thanks for reaching out us

      Is image uploaded to your local folder correctly?

      Delete
  7. How to get document id automaticly?

    ReplyDelete
    Replies
    1. hi, thanks for asking us.

      For new id
      $student = app('firebase.firestore')->database()->collection('Student')->newDocument();

      $student->id();

      hope it helps. And please request you to hit that follow button top left of this blog, to show your support.

      Delete
  8. Unable to determine the Firebase Project ID

    please solve this error

    ReplyDelete
    Replies
    1. hi smedia, thanks for asking query.

      Please follow Chapter 4 and Chapter 5.

      Delete
  9. May i know where the rest of the tutorial is, where you set env variables, install the firebase packages with composer, the Controller "use" script that stores the image to Firebase.

    ReplyDelete
    Replies
    1. Hi Samuel,

      You can find the chapters in sequence.

      Chapter 5 - Integrate Laravel with Google Firebase connecting Cloud Firestore

      https://laravelwithfirebase.blogspot.com/2020/02/chapter-5-integrate-laravel-with-google-firebase-connecting-cloud-firestore.html?m=1

      Delete
  10. How I can call getDownloadURL() function for current uploaded image from "$imag" variable. I have mentioned below.


    $image = app('firebase.storage')->getBucket()->upload($uploadedfile, ['name' => $firebase_storage_path . $file]);

    ReplyDelete
    Replies
    1. Hi

      Can you check this immediate next chapter to fetch image.

      https://laravelwithfirebase.blogspot.com/2020/08/chapter-20-fetch-delete-image-from-firebase-storage-using-laravel-php.html

      Please hit follow button to support our blog.

      Delete
    2. I want to get from the response of uploaded with default function.

      Delete
    3. I don't want to give the expire time I need life time that source. Therefore I want to get the downloadUrl() from response.

      Delete
    4. I think, the app getBucket upload function response will give the relative path I.e half path only.

      One thing you can do give expire time of 1 year.

      If anyone knows better solution pls help.

      Thanks

      Delete
  11. Hi it doesnt upload in Carousel folder rather it's just uploads in the root place.

    $image = $request->file('image'); //image file from frontend
    $carou = app('firebase.firestore')->database()->collection('Carousel')->newDocument();
    $firebase_storage_path = 'Carousel/';
    $name = $carou->id();
    $localfolder = public_path('firebase-temp-uploads') .'/';
    $extension = $image->getClientOriginalExtension();
    $file = $name. '.' . $extension;
    if ($image->move($localfolder, $file)) {
    $uploadedfile = fopen($localfolder.$file, 'r');
    app('firebase.storage')->getBucket()->upload($uploadedfile, ['image' => $firebase_storage_path . $file]);
    //will remove from local laravel folder
    unlink($localfolder . $file);

    return redirect('/carousel');
    } else {

    }

    ReplyDelete
    Replies
    1. We have used $name and you have used $file
      image' => $firebase_storage_path . $file

      May be that be the cause. Can you try checking once if that helps.

      Delete