File storage issue - php

I have recently started to work with laravel voyager admin package, and I have an issue about file upload mechanism.
Firstly, I have create a folder on media menu "contacts":
https://i.imgur.com/fkaVqBz.png
After that, I have made a controller to deal with the contact form and which they can upload their curriculum vitae:
https://i.imgur.com/ckCCSOH.png
In my ContactController, I have made some validations regarding the uploaded file, and some modifications on the name of the uploaded file if the user send the post request:
<?php
namespace App\Http\Controllers;
use App\Contact;
use Illuminate\Http\Request;
use App\Rules\Captcha;
class ContactController extends Controller
{
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function PostContact(Request $request) {
//
$this->validate($request, [
'nom' => 'required|min:2|max:50',
'prenom' => 'required|min:2|max:50',
'email' => 'required|email',
'organisme' => 'required',
'fonction' => 'required',
'pays' => 'required',
'ville' => 'required',
'telephone' => 'required|numeric|',
'objet' => 'required',
'fichier' => 'sometimes|nullable|mimes:doc,docx,pdf',
'g-recaptcha-response' => new Captcha(),
'message' => 'required|min:10']);
$contact = new Contact;
$contact->nom = $request->input('nom');
$contact->prenom = $request->input('prenom');
$contact->organisme = $request->input('organisme');
$contact->fonction = $request->input('fonction');
$contact->pays = $request->input('pays');
$contact->ville = $request->input('ville');
$contact->email = $request->input('email');
$contact->telephone = $request->input('telephone');
$contact->objet = $request->objet;
if ($request->hasFile('fichier')) {
$filenameWithExt = $request->file('fichier')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('fichier')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('fichier')->storeAs('contacts', $fileNameToStore);
$contact->fichier = $path;
}
$contact->message = $request->input('message');
$contact->save();
return redirect('contact')->with('status', 'Votre message a été envoyé avec succès !!');
}
}
The CV file is successfully uploaded but not in the right destination, and contacts folder is creation in storage\app:
https://i.imgur.com/YPpzfCD.png
https://i.imgur.com/KV2CNXo.png
When I create a new contact via voyager admin panel (contact bread)
https://i.imgur.com/Q3GBom8.png, the file uploaded goes into public\contacts\month-year-folder (May2019)\
and this is what I hope to do also using my contact form.
https://i.imgur.com/bFKSKzq.png
Can someone help me solving this issue?
PS: the command php artisan storage:link
indicate that the "public/storage" directory already exists.
Also, I will show any file content if needed
Thanks.

First add a new entry in disks section of config/filesystem.php file
'contacts' => [
'driver' => 'local',
'root' => public_path('contacts'),
'url' => env('APP_URL').'/contacts',
'visibility' => 'public',
],
Then in your controller change the line
$path = $request->file('fichier')->storeAs('contacts', $fileNameToStore);
to
Storage::disk('contacts')->putFileAs($monthYear, $request->file('fichier'), $filename)
Of course you have to calculate your $monthYear variable to compute the subfolder name.

Regarding #Leonardo Rossi's comment, I have resolved this issue by adding this into my config/filesystem.php:
'contacts' => [
'driver' => 'local',
'root' => storage_path('app/public/contacts'),
'url' => '/contacts',
'visibility' => 'public',
],
and in the controller, because the file was stored in the correct folder, I have tried to get the path and then store it in database field (fichier) like that:
if ($request->hasFile('fichier')) {
$filenameWithExt = $request->file('fichier')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('fichier')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
/* $path = $request->file('fichier')->storeAs(public_path('contacts'), $fileNameToStore); */
$now = new \DateTime('now'); //Datetime
$monthNum = $now->format('m');
$dateObj = DateTime::createFromFormat('!m', $monthNum);
$monthName = $dateObj->format('F'); // Month
$year = $now->format('Y'); // Year
$monthYear = $monthName.$year;
Storage::disk('contacts')->putFileAs($monthYear, $request->file('fichier'), $fileNameToStore);
$path = Storage::disk('contacts')->url($monthYear.'/'.$fileNameToStore);
$contact->fichier = $path;
}
You can also have an idea of how can you create a folder using datetime elements (Month+Year) for my case.
Thanks.

Related

How to upload a file in the host with storage?

I wanted to ask what is it like to upload to a host and save it? Of course in the storage folder
Why does this source of mine upload in localhost but not in Host?
But it does not upload at all in the host.
public function store(Request $request)
{
$path = $request->file('image') ?? null;
if ($request->hasFile('image'))
{
$file = $request->file('image');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs('images/aboutExhibitions', $fileName, 'public');
}
AboutExhibition::query()->create([
'user_id' => auth()->id(),
'title' => $request->title,
'link' => $request->link,
'image' => $path,
'options' => $request->options,
'body' => $request->body,
]);
return redirect()->route('admin.aboutExhibitions.index');
}
In the meantime, when I was inside the localhost, I executed the following command before.
php artisan storage:link
Hope this will work.
$image = $request->image;
$image_name=uniqid().date('dmYhis');
$ext=strtolower($image->getClientOriginalExtension());
$image_full_name=$image_name.'.'.$ext;
$image_url=$upload_path.$image_full_name;
$success=$image->move($upload_path,$image_full_name);
$data = array();
$data['image']=$image_url;
$store = Custom::create($data);

i have problem with laravel fileupload image

can someone help me, i want to add article with image. image has successfully entered the directory but in the database the name is always D:\xampp\tmp\php......tmp.
I have changed the system file to public.
Controller
public function store(Request $request)
{
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
}
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Try this
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
}
The reason why it's return a path instead of url because you're using public_path instead of url()
Controller Code
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail')){
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
}else{
$fileName = null;
}
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Run php artisan storage:link, if not created
In blade you can get your file like this
I hope this helps. :D
thanks for your answer my problem has been solved with code like this, but only the name of the file stored in the database not with the name of the directory.
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}

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
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();

How to upload file on another url folder

I am working on xampp localhost. I have a laravel setup. and I am uploading a file from my project to another laravel project.
public function cvupload(Request $request)
{
$this->validate($request,[
'resume' => 'required|mimes:doc,pdf,docx'
],
[
'required' => 'This field is required',
'mimes' => 'Allowed only doc,pdf,docx',
]);
$image = $request->file('resume');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = 'http://example.com/adminapi/app/storage/uploads/';
$image->move($destinationPath, $name);
$resume_with_path = $destinationPath.$name;
}
i gives error
Symfony\Component\HttpFoundation\File\Exception\FileException Unable to create the directory.

My profile picture doesn't show in Laravel 6

I'm learning to create some forum, but when I update a photo profile, it can't show. When I try to inspect element it says:
"Failed to load resource: the server responded with a status of 404 (Not Found)"
This is my Controller:
public function update()
{
$avatar = request()->file('avatar');
$avatar_validate = 'image|mimes:jpeg,png,jpg,svg|max:2048';
request()->validate([
'username' => 'required|alpha_num|min:6|max:20|unique:users,username,' . auth()->id(),
'name' => 'string|required',
'avatar' => $avatar ? $avatar_validate : "",
]);
$hash = auth()->user()->hash;
$avatar_name = $avatar->storeAs('profile-picture', "{$hash}.{$avatar->extension()}");
auth()->user()->update([
'username' => request('username'),
'name' => request('name'),
'avatar' => $avatar_name,
]);
return redirect()->route('users.show', auth()->user()->usernameOrHash());
}
Try this:
$hash = auth()->user()->hash;
$filename = $hash . $avatar->getClientOriginalExtension();
$avatar_name = $avatar->storeAs('profile-picture', $filename);
Also maybe you have some "trash" files stored with a weird filename in your "profile-picture" directory

Categories