hasFile function not working in laravel 5.4 - php

i am trying to upload a photo using Image Intervention Package
i tried dd($request->hasFile('avator') ) and it return false
i returned "error" in my if statment just to make sure that i have an error
thanks in advance
public function update_photo(Request $request){
if($request->hasFile('avator') ){
$avator = $request->file('avator');
$filename = time() . '.' . $pic->getClientOriginalExtension();
Image::make($avator)->resize(300 , 300)->save(public_path('/uploads/avators' . $filename));
$user = Auth::user();
$user->avator = $filename ;
$user->save();
echo "hello world !";
}else {
echo " Error"; // just to make sure that i have an error
}
return view("profile" , array("user" => Auth::user() ));
}

first edit this line of code
$filename = time() . '.' . $avator->getClientOriginalExtension();
add to this slash also
Image::make($avator)->resize(300 , 300)->save(public_path('/uploads/avators/' . $filename));
*in your blade template make sure of spelling you are writing avator not avatar *
<input type="file" name="avator"/>

In your blade put this in your form tag:
enctype="multipart/form-data
and in your controller:
use File;

Related

laravel how to delete file in storage when we delete data

I have some problem to delete file when some value deleted.
This is my delete function:
public function delete($id, Adopsi $adopsi)
{
Storage::delete('post/adopsi/' . $adopsi->image_post_adps);
$data = Adopsi::where('id', $id)->delete();
if ($data) {
return redirect()->route('adopsi.index')->with('success', 'Data telah dihapus');
} else {
return redirect()->route('adopsi.index')->with('error', 'Data gagal dihapus');
}
}
This is how I store my image before:
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$request->file('image_post_adps')->storeAs('public/post/adopsi', $imageName);
directory folder where is use to save:
storage/app/public/post/adopsi/..... (there's my file),
I've used Storage::delete() and unlink() but it still isn't working.
Your images are stored at 'public' disk path. But disk is not specified in delete()
Try
Storage::disk('public')->delete('post/adopsi/' . $adopsi->image_post_adps);
First, make sure the file exists by building the path:
First of all, add the File Facade at the top of the controller:
use Illuminate\Support\Facades\File;
You can use public_path() & storage_path():
$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path)) {
File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}
$path = storage_path().'/app/public/post/adopsi/'.$db->image;
if(File::exists($path)) {
File::delete($path);
}
The below worked for me
$destinationPath = storage_path() . '/app/public/images/products';
File::delete($destinationPath . '/' . $product->id . '.' . $fileExtension);

Laravel show all images from folder

I upload from vue 4-5 images to different folders in laravel.
public function uploadImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$name = $o2order->contactname;
$name2 = str_replace(' ', '_', $name);
$image = $request->file('file');
$imageName = $name2.'.'.time().'.'.$image->extension();
$wwwPath = 'https://api2.api.sk/storage/';
$image->move(storage_path('app/o2/servisne' . '/' . $name2),$imageName);
$imagePath = 'https://api2.api.sk/storage/app/o2/' . ('servisne' . '/' . $name2);
$o2order->servisny = $imagePath;
$o2order->save();
}
This is working fine. In storage/app/o2/servisne_listy/ is folder created and multiple images stored. In sql is written full path to this folder.
I need to show this image or images, sometimes its one sometimes more, not same.
I have this:
public function showImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$servisny = $o2order->servisny;
return response()->json(['servisny' => $servisny], 200);
}
Its shows only the path from sql, but i need path to every file which is in this directory.
Thanks
May be this help you
$path = storage_path('app/o2/servisne');
$files = File::files($path)

File::deleteDirectory('path') does not remove the directory

I'm trying to remove a folder with images in it.
here is my method for removing the file
public function deleteCar($id) {
$car = Car::find($id);
$carImages = carImage::where('car_id', $id);
foreach ($carImages as $image) {
//Just for testing purposes.
$image->car_image_path = '/uploads/cars/32/exampleImage.png';
$pathWords = explode('/', $image->car_image_path);
$path = $pathWords[0] . '/' . $pathWords[1] . '/' . $pathWords[2] . '/' . $pathWords[3];
File::deleteDirectory($path);
$image->delete();
}
$car->delete();
return response()->json(['error' => false, 'data' => $id]);
}
What I want to accomplish is to remove the folder and then the model with the correct car_id. That is passed.
The folder does not get removed and neither does the image model.
You have to use public_path to delete directory:
File::deleteDirectory(public_path('uploads/cars/32'));
The method will return true if it succeeds, false if it fails.
Hope it helps

Files with cyrillic letters in name public storage could not be retrieved in Laravel

I'm getting Object not found error if file contains Cyrillic letters in it's name.
I'm using standard configuration with public storage and symbolic link to public directory and retrieving url to file using following code:
$url = Illuminate\Support\Facades\Storage::disk(config('filesystems.default'))
->url($file->getDiskPath());
Thank you for your help, in advance!
Finally I come up to some solution which fits my needs. Hope it will help someone who face it in future:
First of all I added support of slug for my item. Luckily I was already using Spartie/laravel-tags package and it was as easy as add HasSlug trait to my model.
Then I wrote function which gave me url like:
baseUrl + '/get-item/' + item.slug.en + '/' + item.item_media.id
After then I created controller to catch GET request to that URL:
public function getItem($slug, $mediaId)
{
$media = Media::find($mediaId);
if($media !== null){
$fileName = $media->filename;
$filePath = $media->directory;
$fileExt = $media->extension;
$fileMime = $media->mime_type;
$path = Storage::disk(config('filesystems.default'))->path($filePath . '/'. $fileName . '.' . $fileExt);
if(!File::exists($path)) abort(404);
$headers = array(
'Content-Type: ' . $fileMime,
);
return response()->download($path, $fileName, $headers);
}
}
Of course $slug parameter is redundant in controller definition, but having this string in URL is very useful for SEO purposes.
Update
Problem was not in Russian (or Cyrillic in route). In fact Larave does handle it correctly in route. The actual issue wasn in encoded special characters as per (laravel. Replace %20 in url) and following link gave me a hint to resolve in in very elegant way:
I rewrited url to following:
baseUrl + '/download?file=' + directory + filename + '.' + extension
after that my controller method changed as following:
public function getItem(Request $request)
{
$media = null;
if($request->has('file')) {
$name = $request->get('file');
$media = Media::forPathOnDisk(config('filesystems.default'), $name)->first();
}
if($media !== null){
$fileName = $media->filename;
$filePath = $media->directory;
$fileExt = $media->extension;
$fileMime = $media->mime_type;
$path = Storage::disk(config('filesystems.default'))->path($filePath . '/'. $fileName . '.' . $fileExt);
if(!File::exists($path)) abort(404);
$headers = array(
'Content-Type: ' . $fileMime,
);
return response()->download($path, $fileName, $headers);
}
}

Uploading a file into a Google Drive folder with PHP

I have successfully uploaded a file into Google Drive. However, I'm still not sure on how to upload it into a folder. I need to upload it into a folder structure which looks like this:
Stats
ACLLeauge
ACLSydney
Sorted
Unsorted
{Username}
{FileHere}
The {Username} field is a variable that I will pass through. The {FileHere} field is where the image needs to go. Here is my current code:
public function __construct()
{
$this->instance = new \Google_Client();
$this->instance->setApplicationName('DPStatsBot');
$this->instance->setDeveloperKey(Config::getInstance()->getDriveDeveloperKey());
$this->instance->setAuthConfigFile(Config::getInstance()->getClientSecret());
$this->instance->addScope('https://www.googleapis.com/auth/drive');
if(!file_exists(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile())) {
Printer::write('Please navigate to this URL and authenticate with Google: ' . PHP_EOL . $this->instance->createAuthUrl());
Printer::raw('Authentication Code: ');
$code = trim(fgets(STDIN));
$token = $this->instance->authenticate($code);
file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $token);
Printer::write('Saved auth token');
$this->instance->setAccessToken($token);
}
else
{
$this->instance->setAccessToken(file_get_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile()));
}
if($this->instance->isAccessTokenExpired())
{
$this->instance->refreshToken($this->instance->getRefreshToken());
file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $this->instance->getAccessToken());
}
$this->drive_instance = new \Google_Service_Drive($this->instance);
}
public function upload($image, $dpname)
{
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($dpname . '_' . RandomString::string() . '.jpg');
$upload = $this->drive_instance->files->insert($file,
[
'data' => $image,
'mimeType' => 'image/jpg',
'uploadType' => 'media'
]);
return $upload;
}
If anyone has a suggestion please tell me!
Thanks
For this you have insert the folders in the order you wanted. So add the Stats under the Drive root folder and then add all the folders in the order you needed. For adding a folder, you need to give mimeType as 'application/vnd.google-apps.folder'. Check this link for more mimeType values. Here is an external referring link on how to insert a folder in Drive.
After adding all the required folders you can now insert the actual file under the {Username} folder. You can also refer to this page on how to insert a file in Drive.
Hope that helps!

Categories