Skip image validation and creation in laravel update function - php

Please am trying to upload 3 different images using the code below. How do I get each of the methods that generates the unique image names to run only when their respective request fields have data or is not empty. thus the form submit should not try generating any image name for afile field when that particular file field is empty.
My update controller function
public function update(Request $request, Product $product)
{
$image = $request->file('primary_image');
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$image_1 = $request->file('image_1');
$name_gen = md5(rand(1000, 10000)).'.'.$image_1->getClientOriginalExtension();
Image::make($image_1)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_1 = 'upload/products/'.$name_gen;
$image_2 = $request->file('image_2');
$name_gen = md5(rand(1000, 10000)).'.'.$image_2->getClientOriginalExtension();
Image::make($image_2)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url_2 = 'upload/products/'.$name_gen;
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'image_1' => $save_url_1,
'image_2' => $save_url_2,
]);
$notification = array(
'message' => 'Product updated successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Thanks so much for taking time to review my code

Since you are doing the same name generation process all through, you can use an array and do a foreach loop with an if condition like this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
foreach($my_array as $item) {
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
}
Now this will only generate names for images that are not empty.
UPDATE:
For the insert functionality, I would assume your table fields for the images can have null values, so this doesn't throw an error. Now instead of the code above, do this:
$my_array = [$request->file('primary_image'), $request->file('image_1'), $request->file('image_2')];
$insert_array = [];
foreach($my_array as $item) {
$save_url = '';
if($item) {
$image = $item;
$name_gen = md5(rand(1000, 10000)).'.'.$image->getClientOriginalExtension();
Image::make($image)->resize(523,605)->save('upload/products/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
}
array_push($insert_array, $save_url);
}
Now for your insert query, do this:
Product::insert([
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $insert_array[0],
'image_1' => $insert_array[1],
'image_2' => $insert_array[2],
]);
This would work.

Related

How to attach different picture for each product type

I am building an eCommerce website and I want to add different combinations for the same product.
I use jQuery to add extra input fields as well.
I can successfully insert all data related to product_variation things like color, weight, type, qty but except images.
My database tables: products, product_images, product_variations.
In product_variations table I have field product_variation_image which I want to use for storing image for specific product type. I just don't know how to insert image there for specific product type, yes I know I need to use foreach loop but the problem is I'm already using foreach loop for product variation data, I tried so many different things nesting foreach into foreach but nothing seems to work.
P.S product_images table I'm only use for product basic images also for products which don't have any type.
I will leave my code below... with some comments on where the problem might be.
public function product_store(Request $request)
{
// PRODUCT TYPE VARIABLES //
$productTypes = $request->product_type;
$productColors = $request->product_color;
$productWeight = $request->product_weight;
$productQtys = $request->product_qty;
$productPrices = $request->product_variation_price;
$productTypeImages = $request->file('product_variation_image');
// PRODUCT TYPE VARIABLES ENDS //
// PRODUCT COVER IMAGE //
$productCoverImage = $request->file('product_cover_image');
$productCoverImageNewName = hexdec(uniqid()).'.'.$productCoverImage->getClientOriginalExtension();
Image::make($productCoverImage)->resize(917,1000)->save('upload/products/cover-images/'.$productCoverImageNewName);
$productCoverImageLink = 'upload/products/cover-images/'.$productCoverImageNewName;
// PRODUCT COVER IMAGE ENDS //
if(!empty(implode($productTypes))) {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
]);
// PRODUCT TYPE IMAGES //
foreach ($productTypeImages as $img) {
$productTypeImagesNewName = hexdec(uniqid()) . '.' . $img->getClientOriginalExtension();
Image::make($img)->resize(917, 1000)->save('upload/products/product-images/' . $productTypeImagesNewName);
$productTypesImagesLink = 'upload/products/product-images/' . $productTypeImagesNewName;
}
// PRODUCT TYPE IMAGES ENDS //
foreach ($productTypes as $id => $key) {
ProductVariations::insert([
'product_id' => $productId,
'product_type' => $productTypes[$id],
'product_color' => $productColors[$id],
'product_weight' => $productWeight[$id],
//'product_variation_image' => $productTypesImagesLink[$id], <--- PROBLEM HERE
'product_variation_qty' => $productQtys[$id],
'product_variation_price' => $productPrices[$id],
'created_at' => Carbon::now()
]);
}
} else {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
'created_at' => Carbon::now()
]);
}
// PRODUCT MULTIPLE IMAGES //
$productImages = $request->file('product_image');
foreach ($productImages as $productImage) {
$productImagesNewName = hexdec(uniqid()).'.'.$productImage->getClientOriginalExtension();
Image::make($productImage)->resize(917,1000)->save('upload/products/product-images/'.$productImagesNewName);
$productImagesLink = 'upload/products/product-images/'.$productImagesNewName;
ProductImages::insert([
'product_id' => $productId,
'product_image' => $productImagesLink,
'created_at' => Carbon::now()
]);
}
// PRODUCT MULTIPLE IMAGES ENDS //
$notification = array(
'message' => 'Product Inserted!',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
I have come up with different solution.
After inserting product with multiple images and if product has any variations, I redirect user to another page. Where he can select image for each type if he wants to. And I'm inserting only image id from product_images table, to product_variations table field - product_variation_image.
By the way, I use a jQuery plugin called image-picker for that. And now everything works and my client is happy with that.
Product function:
public function product_store(Request $request)
{
// PRODUCT TYPE VARIABLES //
$productTypes = $request->product_type;
$productColors = $request->product_color;
$productWeight = $request->product_weight;
$productQtys = $request->product_qty;
$productPrices = $request->product_variation_price;
$productTypeImages = $request->file('product_variation_image');
// PRODUCT TYPE VARIABLES ENDS //
// PRODUCT COVER IMAGE //
$productCoverImage = $request->file('product_cover_image');
if($productCoverImage) {
$productCoverImageNewName = hexdec(uniqid()) . '.' . $productCoverImage->getClientOriginalExtension();
Image::make($productCoverImage)->resize(917, 1000)->save('upload/products/cover-images/' . $productCoverImageNewName);
$productCoverImageLink = 'upload/products/cover-images/' . $productCoverImageNewName;
} else {
$productCoverImageLink = 'upload/no-image/image.png';
}
// PRODUCT COVER IMAGE ENDS //
if(!empty(implode($productTypes))) {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
]);
foreach ($productTypes as $id => $key) {
ProductVariations::insert([
'product_id' => $productId,
'product_type' => $productTypes[$id],
'product_color' => $productColors[$id],
'product_weight' => $productWeight[$id],
'product_variation_qty' => $productQtys[$id],
'product_variation_price' => $productPrices[$id],
'created_at' => Carbon::now()
]);
}
} else {
$productId = Products::insertGetId([
'category_id' => $request->category_id,
'sub_category_id' => $request->sub_category_id,
'sub_sub_category_id' => $request->sub_sub_category_id,
'product_name' => $request->product_name,
'product_link' => strtolower(str_replace(' ','-', $request->product_name)),
'product_desc' => $request->product_desc,
'product_short_desc' => $request->product_short_desc,
'product_price' => $request->product_price,
'product_discount' => $request->product_discount,
'product_cover_image' => $productCoverImageLink,
'new_product' => $request->new_product,
'featured' => $request->featured,
'special_offer' => $request->special_offer,
'status' => $request->status,
'created_at' => Carbon::now()
]);
}
// PRODUCT MULTIPLE IMAGES //
$productImages = $request->file('product_image');
if($productImages) {
foreach ($productImages as $productImage) {
$productImagesNewName = hexdec(uniqid()) . '.' . $productImage->getClientOriginalExtension();
Image::make($productImage)->resize(917, 1000)->save('upload/products/product-images/' . $productImagesNewName);
$productImagesLink = 'upload/products/product-images/' . $productImagesNewName;
ProductImages::insert([
'product_id' => $productId,
'product_image' => $productImagesLink,
'created_at' => Carbon::now()
]);
}
}
// PRODUCT MULTIPLE IMAGES ENDS //
$notification = array(
'message' => 'Product Inserted!',
'alert-type' => 'success'
);
if(!empty(implode($productTypes))) {
return redirect()->route('admin.product-variations-images-settings', ['id' => $productId])->with($notification);
} else {
return redirect()->route('admin.products')->with($notification);
}
}
Functions for image varations:
public function product_variations_images_settings($id)
{
$productVariations = ProductVariations::where('product_id', $id)->get();
$productImages = ProductImages::where('product_id', $id)->get();
return view('administrator.pages.products.product-variations', compact('productVariations','productImages'));
}
public function product_variations_images_store(Request $request)
{
$productVariationId = $request->id;
$productImageId = $request->product_variation_image;
$array = array_combine($productVariationId, $productImageId);
foreach ($array as $id => $key){
//dd($key);
ProductVariations::findOrFail($id)->update([
'product_variation_image' => $key,
'updated_at' => Carbon::now()
]);
}
$notification = array(
'message' => 'Images Set!',
'alert-type' => 'success'
);
return redirect()->route('admin.products')->with($notification);
}

Drupal 8 Custom Module - From dynamic data (API) to store at Fields (Content type) Drupal DB

I've created a custom module in Drupal 8 that grab some data from an API, and puts them in the Drupal DB creating a new table.
I want to add this data as the contents of a specific content type.
How can I do that?
here is my code :
<?php
/**
* Implements hook_cron().
*/
function ods_cron() {
$message = 'Cron run: ' . date('Y-m-d H:i:s');
$ods = \Drupal::service('ods.ods');
$conf = \Drupal::service('ods.ods_configuration_request');
if ($conf->isDevelopment()) {
// Development
$response_bond = beforeSendRequest($conf->devUrlExternalBond(), 'GET');
$response_mf = beforeSendRequest($conf->devUrlExternalMutualFund(), 'GET');
} else {
// Production
$parameters_bond = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyBond(),
];
$parameters_mf = [
'headers' => $conf->headers(),
'authorization' => $conf->basicAuthorization(),
'data_post' => $conf->bodyMutualFund(),
];
$response_bond = beforeSendRequest($conf->urlExternalBond(), 'POST', $parameters_bond);
$response_mf = beforeSendRequest($conf->urlExternalMutualFund(), 'POST', $parameters_mf);
}
$raw_result_bond = json_decode($response_bond);
$raw_result_mf = json_decode($response_mf);
// Development
if ($conf->isDevelopment()) {
$raw_result_bond = json_decode($raw_result_bond[0]->field_bonds);
$raw_result_mf = json_decode($raw_result_mf[0]->field_api);
}
$BondsProductList = $raw_result_bond->BondsProductInqRs->BondsProductList;
$MFProductInqList = $raw_result_mf->MFProductInqRs->MFProductInqList;
// Bond data store to internal
if ($BondsProductList !== null) {
$bond_datas = [];
foreach ($BondsProductList as $row => $content) {
$bond_datas[] = [
'AskPrice' => number_format($content->AskPrice, 1, '.', ','),
'BidPrice' => number_format($content->BidPrice, 1, '.', ','),
'BuySettle' => number_format($content->BuySettle, 1, '.', ','),
'CouponFreqCode' => $content->CouponFreqCode,
'CouponFreqID' => number_format($content->CouponFreqID),
'CouponRate' => number_format($content->CouponRate, 2, '.', ','),
'IDCurrency' => $content->IDCurrency,
'LastCoupon' => $content->LastCoupon,
'MaturityDate' => $content->MaturityDate,
'MinimumBuyUnit' => number_format($content->MinimumBuyUnit),
'MultipleOfUnit' => number_format($content->MultipleOfUnit),
'NextCoupon' => $content->NextCoupon,
'Penerbit' => $content->Penerbit,
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductAlias' => $content->ProductAlias,
'RiskProfile' => $content->RiskProfile,
'SellSettle' => $content->SellSettle
];
}
$insert_data = $ods->setData(
'bond',
[
'AskPrice', 'BidPrice', 'BuySettle', 'CouponFreqCode', 'CouponFreqID', 'CouponRate', 'IDCurrency',
'LastCoupon', 'MaturityDate', 'MinimumBuyUnit', 'MultipleOfUnit', 'NextCoupon', 'Penerbit',
'ProductCode', 'ProductName', 'ProductAlias', 'RiskProfile', 'SellSettle'
],
$bond_datas
);
if ($insert_data) {
// make response as JSON File and store the file
$ods->makeJsonFile($bond_datas, 'feeds/bonds', 'bond.json');
}
}
// Mutual Fund data store to internal
if ($MFProductInqList !== null) {
$mf_datas = [];
foreach ($MFProductInqList as $row => $content) {
$mf_datas[] = [
'ProductCode' => $content->ProductCode,
'ProductName' => $content->ProductName,
'ProductCategory' => $content->ProductCategory,
'ProductType' => $content->ProductType,
'Currency' => $content->Currency,
'Performance1' => $content->field_1_tahun_mf,
'Performance2' => $content->Performance2,
'Performance3' => $content->Performance3,
'Performance4' => $content->Performance4,
'Performance5' => $content->Performance5,
'UrlProspektus' => $content->UrlProspektus,
'UrlFactSheet' => $content->UrlFactSheet,
'UrlProductFeatureDocument' => $content->UrlProductFeatureDocument,
'RiskProfile' => $content->RiskProfile,
'FundHouseName' => $content->FundHouseName,
'NAVDate' => $content->NAVDate,
'NAVValue' => $content->NAVValue
];
}
$insert_data_mf = $ods->setData(
'mutual_fund',
[
'ProductCode', 'ProductName', 'ProductCategory', 'ProductType', 'Currency', 'Performance1', 'Performance2', 'Performance3',
'Performance4', 'Performance5', 'UrlProspektus', 'UrlFactSheet', 'UrlProductFeatureDocument', 'RiskProfile', 'FundHouseName',
'NAVDate', 'NAVValue'
],
$mf_datas
);
if ($insert_data_mf) {
// make response as JSON File and store the file
$ods->makeJsonFile($mf_datas, 'feeds/mf', 'mutual_fund.json');
}
}
// console log
\Drupal::logger('ods')->notice($message);
}
So can I store the data to pristine drupal 8 table?
First, you need to create the content type in the Drupal 8 backend going to Structure > Content type.
Second you can add a node programmatically like this
use Drupal\node\Entity\Node;
$node = Node::create(array(
'type' => 'your_content_type',
'title' => 'your title',
'langcode' => 'en',
'uid' => '1',
'status' => 1,
'body'=> 'your body',
));
$node->save();

Laravel inserts two user records at register, how to prevent this?

I am creating an application where I have to insert a user at registration with custom fields. As found online, i customised the create method in the Laravel RegisterController. However, now the application inserts two user records whenever I register a new user. Can someone help me with this please?
Here is the code of my create method in the RegisterController
protected function create(array $data)
{
/********************************************************************************
* CALCULATE ALL THE NEEDED DATA FOR THE USER
********************************************************************************/
// Delete the uncompleted registration
UncompletedRegistration::deleteByEmail($data['email']);
// Set the right values based on the filled values
$compercentagecreative = 0.0;
$compercentagenotcreative = 0.0;
$creativepercent = 0.0;
switch ($data['headjob']) {
case 1:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
case 2:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.notheadjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.notheadjob');
$creativepercent = config('constants.percentageRates.creativePercent.notheadjob');
break;
default:
$compercentagecreative = config('constants.percentageRates.comPercentageCreative.headjob');
$compercentagenotcreative = config('constants.percentageRates.comPercentageNotCreative.headjob');
$creativepercent = config('constants.percentageRates.creativePercent.headjob');
break;
}
// Format the VAT number
$data['vatnumber'] = Helper::formatVatNumber($data['vatnumber']);
$isVatValid = false;
try {
// Check if vat is valid
$response = Helper::checkVat($data['vatnumber']);
$responseArray = json_decode($response);
$isVatValid = $responseArray->valid;
} catch (\Exception $exception) {
$isVatValid = false;
}
// Generate an activation key
$activationKey = md5(uniqid('CS', true));
/********************************************************************************
* CREATE THE USER IN THE DATABASE
********************************************************************************/
// Create the user and insert in the database
return User::create([
'usertype' => config('constants.userTypes.USER'),
'registeredon' => strtotime(date("Y-m-d H:i:s")),
'activationkey' => $activationKey,
'language' => 'nl',
'email' => Helper::truncate($data['email']),
'fullname' => Helper::truncate($data['lastname'] . ' ' . $data['firstname']),
'firstname' => Helper::truncate($data['firstname']),
'lastname' => Helper::truncate($data['lastname']),
'password' => Hash::make($data['password']),
'lastloginon' => strtotime('now'),
'lastloginip' => $_SERVER['REMOTE_ADDR'],
'activatedon' => strtotime(date('Y-m-d H:i:s', strtotime('1970-01-01 00:00:00'))),
'deleted' => false,
'companyname' => Helper::truncate($data['companyname']),
'street' => Helper::truncate($data['street']),
'number' => Helper::truncate($data['number']),
'city' => Helper::truncate($data['city']),
'zipcode' => Helper::truncate($data['zipcode']),
'vatnumber' => Helper::truncate($data['vatnumber']),
'validvat' => $isVatValid,
'website' => Helper::truncate($data['website']),
'phonenumber' => Helper::truncate($data['phonenumber']),
'bankname' => Helper::truncate($data['bank']),
'iban' => Helper::truncate($data['iban']),
'bicswift' => Helper::truncate($data['bicswift']),
'paymentremindermode' => $data['paymentremindermode'],
'invoicecreationremindermode' => 2,
'nettosavedmailmode' => 1,
'zombiemailsent' => 0,
'zombiemail180sent' => 0,
'nettosavedperinvoicmailemode' => 1,
'logo' => NULL,
'emailaccepted' => false,
'contractaccepted' => false,
'compercentagecreative' => $compercentagecreative,
'compercentagenotcreative' => $compercentagenotcreative,
'contractdate' => date("Y-m-d H:i:s"),
'creativepercent' => $creativepercent,
'activity' => $data['activity'],
'headjob' => $data['headjob'],
'template' => config('constants.templates.ORIGINAL'),
'freebtw' => isset($data['freebtw']) ? ($data['freebtw'] == "on" ? true : false) : false,
'refid' => Input::get('invite_id'),
'api_key' => Helper::generateRandomString(40),
'allowed_quotation' => true,
'send_bcc' => false
]);
}

Response Customized Object Transaction in Laravel

I've created a transaction but I'd like to return all data which has been created in one json. I'd like to do this using Resources in Laravel 5.5.
This is my transaction:
$firstUser = DB::transaction(function () use ($request) {
//Create Group Campany
$groupCompany = \App\GroupCompany::create([
'name' => $request['nameGroupCompany'],
'cod' => $request['codGroupCompany'],
]);
//Create Company
$company = \App\Company::create([
'group_company_id' => $groupCompany->id,
'name' => $request['nameCompany'],
'cod' => $request['codCompany'],
]);
//Create Group User
$groupUser = \App\GroupUser::create([
'name' => 'Admin',
'admin' => 1,
]);
$groupUser->companies()->attach($company->id);
//Create Person
$person = \App\Person::create([
'firstName' => $request['name'],
'middleName' => $request['middleName'],
'lastName' => $request['lastName'],
'dateOfBirth' => $request['dateOfBirth'],
]);
$person->groupUsers()->attach($groupUser->id);
//Create User
$newUser = \App\User::create([
'person_id' => $person->id,
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
]);
return ??????;
});
And finally I call my Resource:
return new FirstUserResource($firstUser);
What should I do?
Thank you very much.
Marcel
Save info in a array before save them like below:
$groupCompanya = array('name' => $request['nameGroupCompany'],
'cod' => $request['codGroupCompany']);
$groupCompany = \App\GroupCompany::create($groupCompanya);
Gather all data into a new array:
$result = array("groupCompany"=> $groupCompanya, "company" => $companya, "groupUser" => $groupUsera, "person"=>$persona, "newUser"=>$newUsera);
after convert it to json and return it:
$json = array("result" => $result);
return json_encode($json,JSON_UNESCAPED_UNICODE);
If you are returning all the data as a single json I think Collections will help you here?
$collection = collect([var1,var2]);
return $collection->toJson();

Trying to upload multiple images using guzzlehttp client in laravel

I am trying to upload multiple images using guzzlehttp client. I have a form in which other type of data('id', 'date','name' e.t.c..) and images are there.
I want to save other data along with image upload through an Api Request.
I am able to save other data, but i am getting problem in uploading images.
In the API i am accessing my image file by
$request->file('images')
but it is showing empty.
My code for calling the API
$images = $request->file('images');
foreach ($images as $image)
{
$body[] = [
'Content-type' => 'multipart/form-data',
'name' => $image->getClientOriginalName(),
'contents' => fopen($image->getRealPath(), 'r')
];
}
$data = $request->all();
$client = new Client();
$response = $client->request('POST', $url, [
'multipart' => $body,
'json' => $data
]);
I'm handling the Api for uploading image below
if ($request->hasFile('images'))
{
$images = $request->file('images');
foreach ($images as $image)
{
$imageRules = [
'file' => 'mimes:png,jpeg,jpg,JPG|max:1024'
];
$imageMessages = [
'file.mimes' => 'One of the images/video is not valid. (only .png, .jpeg, .jpg, .mp4, .x-flv, .x-mpegURL, .MP2T, .3gpp, .quicktime, .x-msvideo, .x-ms-wmv are accepted)',
'file.max' => 'Image size cannot br more than 1 MB'
];
$imageValidator = Validator::make(['file' => $image], $imageRules, $imageMessages);
if ($imageValidator->fails())
{
return response()->json(['success' => false, 'error' => $imageValidator->messages()->first(), 'dashRedirectUrl' => $redirectRoute]);
}
}
$directPath = '/ticket/' . $ticket->id . '/mapping/' . $mappingId . '/images/';
foreach ($images as $image)
{
$option = ['isWatermark' => false];
$imageName = $this->uploadImageToServer($image, $directPath, $option);
$imgInsertData = [
'url' => $imageName,
'title' => $this->getImageTitle($image),
'ticket_mapping_id' => $mappingId,
'type_id' => 1,
];
TicketMappingGallery::create($imgInsertData);
}
}
Note :: My funciton uploadImageToServer() is custom function for uploading the images..
Any help would be appreciated. Drop comment if anything is not clear.
Try this one,
foreach ($image as $img) {
$body[] = [
'name' => 'image[]',
'image_path' => $img->getPathname(),
'image_mime' => $img->getmimeType(),
'image_org' => $img->getClientOriginalName(),
'contents' => fopen($img->getRealPath(), 'r')
];
}
$requestOptions = ['query' => $data, 'multipart' => $body
];

Categories