How to upload image in array input type - laravel

I want to upload image using protected function create(array $data){}
Below code is used for public function create(Request $request){}
public function create(Request $request)
{
$image = new Image();
if ($request->hasFile('image')) {
$dir = 'uploads/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->image = $fileName;
}
$image->save();
return view('here');
}
}
I tried the following code but gets error
protected function create(array $data)
{
$dir = '/customer/images/';
$extension = strtolower($data['image']->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$data['image']->move($dir, $fileName);
$data['image'] = $fileName;
return Image::create([
'image' => $data['image'],
]);
}
I'm getting error. How can i upload image using array.

Related

How to Delete the previous image from the folder when updated by new image in Laravel

**I want to delete the previous image saved in folder and update new image in laravel What is mistake in this code it doesnt work?**xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
code that stores data and image
public function store(Request $request)
{
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->image->move(public_path('/uploads/image'), $fileNameToStore);
}
else
{
$fileNameToStore = 'No Img Found!';
}
$covidrecord = new Covidrecord();
$covidrecord->fullname = $request->fullame;
$covidrecord->image = $fileNameToStore;
$covidrecord->save();
if( $covidrecord->save())
{
return redirect()->route('store')->with(['msg'=>"User create successfully"]);
return redirect()->route('store')->withError(['msg'=>"User cannot be registerd at the moment"]);
}
}
code to update data and image
public function update(Request $request, $id)
{
$covidrecord = Covidrecord::find($id);
#Check if uploaded file already exist in Folder
if($request->hasFile('product_image'))
{
#Get Image Path from Folder
$path = 'uploads/image/'.$covidrecord->image;
if(File::exists($path))
{
File::destroy($path);
}
#If File is new and not Exist in Folder
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$request->product_image->move(public_path('/uploads/image'), $fileNameToStore);
$covidrecord->product_image = $fileNameToStore;
if($covidrecord->save())
{
dd('Product updated Successfully');
}
else{
dd('Product update Failed');
}
}
}
There is red line in File
The public path method is missing while you are generating a path to check file existence in the update method
$path = public_path().'/uploads/image/'.$covidrecord->image;
if(File::exists($path))
{
File::destroy($path);
}

upload an image through an api using in laravel

i have 2 web systems here,system a and system b.when i upload an image on system a i want as well send the image to system b.i am using an api to achieve the logic.am able to upload the image in system a perfectly but its unable be pushed to system b.am using guzzle http client to send the image to the api on upload.the upload on system a works very well but the data is being saved in system b.i have tested the api store function in postman and i get i 200ok status code but the data isnt being saved in the specific table in system b database.
here is my image save function in system a which works perfectly,it generates a folder which stores the image and a thumbnail folder inside the main folder where the thumbnail is stored.
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system b on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_h2image";
$response = $client->request('POST',$url,[
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => $filename,
'contents' => file_get_contents( public_path() . "/images/product/$product_id/".$filename)
],
]
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = $e->getMessage();
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
here is my route for the api
Route::post(/push_productimage','APIController#savesystemAimage')->name(pushproductimage');
here is the api function in system b where the image and thumbnail should be recieved and stored to system b database
public function savesystemAimage(Request $request)
{
$productdetails=new Product;
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension();
$filename = ('p' . sprintf("%010d", $productdetails->id)) . '-m' . rand(1000, 9999) . '.' . $extension;
$product_id = $productdetails->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail( public_path() . "/images/product/$product_id/" . $filename,
$dest,200);
$systemid = $request->product_id;
$productdetails->photo_1 = $filename;
$productdetails->thumbnail_1 = 'thumb_' . $filename;
$productdetails->save();
}
}
i dont know why the api function is not storing the data yet on postman it shows a 200ok status code but the image and thumbnail isnt saved.

Laravel download image

I have a function to add an image, and upon successful addition in the database, we have a path like public/images/asd.png. The question is how to make sure that when added to the name of the picture, an ID is added, and we have something like public/images/asd1.png, public/images/asd2.png, etc.
function in Model
public function getOriginImageUrl()
{
return $this->attributes['image'];
}
public function getImageAttribute($value)
{
return Storage::exists($value) ? Storage::url($value) : null;
}
function in Controller
if ($request->hasFile('image')) {
$file = $request->file('image');
$blog->image = $file->storeAs('public/images', $file->getClientOriginalName());
}
Instead of id you can combine time() with image name.
if ($request->hasFile('image')) {
$file = $request->file('image');
$namewithextension = $file->getClientOriginalName(); //Name with extension 'filename.jpg'
$name = explode('.', $namewithextension)[0]; // Filename 'filename'
$extension = $file->getClientOriginalExtension(); //Extension 'jpg'
$uploadname = $name. '-' .time() . '.' . $extension;
$blog->image = $file->storeAs('public/images', $uploadname);
}

Image not saving in Database in Laravel

I am trying to store image into database after it has been converted to base64 and also decoded. The image stores inside the Storage path but does not save into mysql database.
What am i doing wrong?
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1]; //generating unique file name;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->all());
}
Try this:
$user = auth('api')->user();
if ($request['image']) {
$data = $request['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$image = base64_decode($data);
$photoName = 'profile' . time() . '.' . $image_extension[1];
$request['image'] = $photoName;
Storage::disk('public')->put($photoName, $image);
$user->update($request->all());
}
I had to do this
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1]; //generating unique file name;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
}
and it worked
I recommend you to use uploader packages like:
https://github.com/spatie/laravel-medialibrary
or
https://github.com/alaaelgndy/FileUploader
to help you in media management without writing all these lines of code in every place you want to upload files.
enjoy them.

Laravel 5 - Image Upload and Resize using Intervention Image Package

I want to upload a photo with some posts.
This is my controller
public function store(WisataRequest $request)
{
$input = $request->all();
if ($request->hasFile('gambar')) {
$gambar = $request->file('gambar');
$filename = time() . '.' . $gambar->getClientOriginalExtension();
if ($request->file('gambar')->isValid()) {
Image::make($gambar)->resize(300, 300)->save(public_path('/upload/gambar/'.$filename));
$input->gambar = $filename;
$input->save();
}
}
$wisata = Wisata::create($input);
Session::flash('flash_message', 'Berhasil Terkirim');
return redirect('admin_wisata');
}
But when it runs i found an error
Attempt to assign property of non-object
Change
$input->gambar = $filename;
$input->save();
To
$input['gambar']= $filename;
$input variable is not an object, it is an array. You can try accessing gambar in $input by doing $input['gambar']
You can put
$input['gambar']= $filename;
Instead of
$input->gambar = $filename;
$input->save();
OR
public function store(WisataRequest $request)
{
$wista = new Wista;
$wist->name = $request->name;
-----
$wista->save();
if ($request->hasFile('gambar')) {
$gambar = $request->file('gambar');
$filename = time() . '.' . $gambar->getClientOriginalExtension();
if ($request->file('gambar')->isValid()) {
Image::make($gambar)->resize(300, 300)->save(public_path('/upload/gambar/'.$filename));
$wista->gambar = $filename;
$wista->save();
}
}
Session::flash('flash_message', 'Berhasil Terkirim');
return redirect('admin_wisata');
}

Resources