How Upload images with cloudinary + Laravel? - php

Well, what happens is that I want to upload an image to Cloudinary through Laravel,
I Follow the steps as it says on the documentation:
https://github.com/cloudinary-labs/cloudinary-laravel
and here : https://cloudinary.com/blog/laravel_file_upload_to_a_local_server_or_to_the_cloud
I am using Laravel 8, here is my code:
public function store(Request $request){
$request->validate([
'name' => 'required|string|unique:festivals|max:255', //unique:table
'description' => 'required|string|max:255',
'image' => 'required|image|dimensions:min_width=200,min_height=200',
], self::$messages);
//Here I create an instance and upload file to server
$festival = new Festival($request->all());
$path = cloudinary()->upload($request->file('image')->getRealPath())->getSecurePath();
dd($path);
//Then at field image of festivals que save the path and that goes to the database
$festival->image = 'festivals/' . basename($path);
$festival->save();
return response() -> json($festival, 201); //code 201 created
}
When I try to create a new record through Postman, this happens:
Error after register new festival
However, the image was uploaded to Cloudinary:
image uploaded
Then I tried to check if the record was created, but it was not created.
What can I do, does anyone know?
Thanks

Ok, I Solved :)
//Here I create an instance and upload file to server
$festival = new Festival($request->all());
$result = $request->image->storeOnCloudinary();
//Here I get the url
$path = $result->getPath();
//Then at field image of festivals que save the path and that goes to the database
//$festival->image = $path; output: "https://res.cloudinary.com/test/image/upload/v1226931211/zuiyb17vfs8dre6gvuov.jpg"
//$festival->image = dirname($path); output: "https://res.cloudinary.com/test/image/upload/v1526711711"
//$festival->image = basename($path); output: "zuiy31lvfs4dre5gvuov.jpg"
$base = basename(dirname($path).basename($path)); //output: "v1636941221zuiyb14vfsmdre6gvuov.jpg"
$folder = substr($base, 0, -24); //output: "v1626915261"
//So:
$img_path = $folder.'/'.basename($path);
$festival->image = 'festivals/'.$img_path; //imageFolder/imageName.jpg;
But if someone has a best way, please tell me

Related

laravel upload file 0 byte on the server

I use below script to uploade a file to the sevre. it works fine on the local host (wamp server), but when I try to use it on the server I figure out that the uploaded file size is 0 byte.
Any one know taht where is the problem?
public function uploadFile(Request $request)
{
$request->validate([
'name' => 'required',
'auther_id'=>'required',
'doc_type'=>'required',
'file'=>'required|mimes:pdf'
]);
$fileModel = new File;
$fileName = time().'_'.$request->file->getClientOriginalName();
$filePath = $request->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = time().'_'.$request->file->getClientOriginalName();
$fileModel->file_path = '/storage/' . $filePath;
$fileModel->save();
}
I think you can use like this. first of all you need to store your file inside storage. then you can get public url from storage.
Try this way
$fileName = time().'_'.$request->file->getClientOriginalName();
Storage::put('/public/uploads/'.$fileName,$request->file('file'));
$url = Storage::url('public/uploads/'.$fileName);
$fileModel = new File;
$fileModel->name = time().'_'.$request->file->getClientOriginalName();
$fileModel->file_path = $url;
$fileModel->save();
Reason of this error was permissions of some folders. I just reset the host completely and now everything work like a charm.

Error in uploading image when using cpanel

when developing locally, i was able to upload images in storage directory, but now as the diectory sructure changed a bit.
Now Intervention is showing an error.
Error is
message: "Image source not readable", exception: "Intervention\Image\Exception\NotReadableException",…}
exception: "Intervention\Image\Exception\NotReadableException"
This is my controller
public function submitAddProduct(Request $request){
$data = $request->validate([
'image' => ['required','image'],
'image_second' => ['required','image']
]);
//dd(request('image')->store('uploads','public'));
$imagePath = request('image')->store('uploads','public');
$image = Image::make(public_path("storage/{$imagePath}"));
$image->save();
$imagePath2 = request('image_second')->store('uploads','public');
$image2 = Image::make(public_path("storage/{$imagePath2}"));
$image2->save();
$dataVal = $request->all();
$dataVal['image'] = $imagePath;
$dataVal['image_second'] = $imagePath2;
// d3d($dataVal);
$d = Products::create($dataVal);
$id = $d->id;
if($id){
$arr = array('msg' => $id);
}
return Response()->json($arr);
}
it should get stored in the uploads directory.
My cpanel directory structure is as follows
The public_html contains
And the system folder inside the public_html contains
The symlinks are working fine, as i can see images that were previously present in uploads.
symlink.php is
<?php
symlink('/home//public_html/system/storage/app/public','/home//public_html/storage');
Only the first Image gets uploaded to storage/uploads and then interventions shows error.
Please Help

Laravel Image Update

I'm doing a Admin Panel in Laravel 5.6 and I have a problem where productController --resource update.
My store as this:
if($request->hasfile('filename'))
{
$file = $request->file('filename');
$name=$file->getClientOriginalName();
$image_resize = Image::make($file->getRealPath());
$image_resize->resize(590, 590);
$image_resize->save(public_path('/images/urunler/' .$name));
}
$urun = new Urun();
$urun->k_id=$request->get('k_id');
$urun->ad=$request->get('ad');
$urun->form=$request->get('form');
$urun->icerik=$request->get('icerik');
$urun->ticari_sekli=$request->get('ticari_sekli');
$urun->filename=$name;
$urun->save();
return redirect('/urunler')->with('success','Ürün Başarı İle Eklendi.');
and My Update as this:
$urun= Urun::findOrFail($id);
$urun->update($request->all());
if ($request->hasFile('filename'))
{
$file = $request->file('filename');
$name=$file->getClientOriginalName();
$img = Image::make($file->getRealPath());
$img->resize(590, 590);
$img = Image::make($file->getRealPath())->resize(590, 590)->insert(public_path('/images/urunler/' .$name));
$img->save(public_path('/images/urunler/' .$name));
$urun->image = $name;
}
$urun->save();
return redirect('/urunler')->with('success','Ürün Başarı İle Güncellendi.');
Store part is working but Update part save a filename database but image doesn't move in images/urunler.
My php version is 7.2.4 and I'm using Laravel 5.6.
Delete these codes.
$img = Image::make($file->getRealPath())->resize(590, 590)->insert(public_path('/images/urunler/' .$name));
$img->save(public_path('/images/urunler/' .$name));
After that. Add these codes.
$location = public_path('/images/urunler/'.$name);
Image::make($file->getRealPath())->resize(590, 590)->save($location);
Give it a try.
Solution: Change related codes like that.
$location = public_path('/images/urunler/'.$name);
Image::make($file->getRealPath())->resize(590, 590)->save($location);
$urun->filename= $name;
Then add
$this->validate(request(),[
'k_id' => 'required',
'ad' => 'required',
'form' => 'required',
'icerik' => 'required',
'ticari_sekli' => 'required',
'filename'=>'required' ]);
PS: filename must be just required. Not required|image. It isn't an image. Its just name.
After that request filename. Like that: $urun->filename= $name;
don't $urun->image= $name;. Because there is no $urun->image.
This works for me:
if ($request->file('filename')) {
$file = $request->file('filename');
$destinationPath = $_SERVER['DOCUMENT_ROOT'] . '/images/urunler/';
$file->move($destinationPath, 'FILENAME.' . $file->getClientOriginalExtension());
}
Just edit FILENAME to the name of the file you want or replace FILENAME with $file->getClientOriginalName();
The file wil be saved in the public/images/urunler/ folder
EDIT:
Last thing i can think of would be this: in the form open tag place enctype="multipart/form-data". What this says is that your form exists of normal data AND possible files. There might still be files are not allowed so also place files="true"in the form open.

Cannot upload image in Laravel 5.2

I make input data with an upload image, my code
$name = $request->input('name');
$images = $request->file('image');
$name_img = $images->getClientOriginalName();
$ext = $images->getClientOriginalExtension();
// Move Uploaded File
$destinationPath = 'img/';
$images->move($destinationPath,$name_img);
$path = $destinationPath.'/'.$name_img;
then put them in array, then insert in database
$data = array(
'name' => $name,
'image' => $path, );
DB::table('daftar')->insert($data);
return json_encode(array('status' =>true));
That code works in Laravel 5.1, but it doesnt work in Laravel 5.2.
Anything wrong with that code for Laravel 5.2?
Thank You. :)
I am using this approach and it work:
//Use should have use App\Daftar in above your class;
//Your method inputs should be like UploadRequest $request , Daftar $daftar
$file=$request->file('image');
$name=time().'-'.$file->getClientOriginalName();
$path = public_path().'/img';
$file->move($path, $name);
$daftar->create(array('name' => $name, 'image' => $path));
Ensure that in the table was not a field that can not be empty
you cal learn more about public_path() here:
https://laravel.com/docs/5.5/helpers#method-public-path
Also my Upload folder is on public directory
if you want to ensure that data saved in the database is the same as you send check with following approach:
//Use should have use App\Daftar in above your class;
//Your method inputs should be like UploadRequest $request , Daftar $daftar
$file=$request->file('image');
$name=time().'-'.$file->getClientOriginalName();
$path = public_path().'/img';
$file->move($path, $name);
print 'name is'.$name.' and image is '.$path;
$daftar->create(array('name' => $name, 'image' => $path));
And after that check the data that saved in the database both data should be same.

How to save a image filecontent into the SQL database using eloquent?

I'm getting confused about how to save an image content inside of a database table.
Please see the fourth line of code. I'm sure that this restful method (using POST) is working because getSize() returns the true value.
Also, if I debug what returns the 5th line I get something like the next one:
So, I'm not sure if what am I missing to save this data into the database.
$personId = Input::get('PersonId');
$file = Input::file('media');
$tmppath = $file->getRealPath();
$content = file_get_contents($tmppath); //$file->getSize();
// return $content;
$model = Person::find($personId);
$model->Photo = $content;
$model->save();
$result = array(
"success" => true,
"data" => $personId,
"error" => ""
);
You need to save the file to the server and only store the path in the database.
Write an appropriate method, ideally you can store it in a trait.
private function saveFileToDisk($file, $fileName)
{
$path = public_path() . '/uploads/';
return $file->move($path, $fileName . $file->getClientOriginalExtension());
}
An then pass the file input to your method and provide a name for the file:
$model->Photo = $this->saveFileToDisk(Input::file('media'), $model->Name);
Obvisouly you need to validate you input before all this.

Categories