How to upload file in firebase storage using laravel?
This guide will walk you through the integration process, ensuring a seamless and secure file upload experience for your web application.
We will not be covering the basics of connecting and obtaining credentials. For those foundational steps, please refer to our previous posts on setting up and connecting your project with Laravel. Additionally, we've covered CRUD operations in another post, so be sure to check that out as well.
- Connecting and setting up authentication.
We will assume that the basics are completed and that you are already familiar with CRUD operations. Therefore, simply use the code below to upload a file for a new record.
$storeArray = [
'name' => $request->name,
];
$imageLink = null;
$imageName = null;
if ($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStores = $filename . '_' . time() . rand(1000,9999) . '.' . $extension;
$uploadedFile = fopen($request['image'], 'r');
$imageReference = firebaseStorage()->getBucket()->upload($uploadedFile, ['name' => 'uploads/'.'category'.'/'.$fileNameToStores]);
$expiresAt = new \DateTime('2099-12-31');
$imageLink = $imageReference->signedUrl($expiresAt);
$imageName = $fileNameToStores;
}
$storeArray['image_url'] = $imageLink;
$storeArray['image_name'] = $imageName;
You might be wondering what the 'firebaseStorage' function is. It's a custom function that we'll create in 'app/Services/firebase.php'. If you're unfamiliar with this custom helper, please refer to our previous post.
if (!function_exists('firebaseStorage'))
{
function firebaseStorage()
{
$db = (new Factory)->withServiceAccount(__DIR__ . '/service.json')->createStorage();
return $db;
}
}
We've uploaded the file, but when we do so, we need to delete the previous file. To delete a file use the code below.
if (isset($snapshot['image_name']) && !empty($snapshot['image_name']))
{
$oldFile = firebaseStorage()->getBucket()->object('uploads/'.'category'.'/'.$snapshot['image_name']);
if ($oldFile->exists())
{
$oldFile->delete();
}
}
Related Posts
How to implement firebase google authentication in laravel?
How to upload file in firebase storage using laravel?
How to integrate Firebase with Laravel and set up authentication?
How to implement firebase phone authentication in laravel?
How to create a firebase project and obtain configuration file?
How to perform CRUD operations in Firebase using Laravel?