I'm trying to import an excel to my database table 'barangs' but it has an error saying "Illegal string offset 'kode_barang'". i dont know again to fix this error.
import data from excel to database with laravel maatwebsite
my controller
public function import(Request $request)
{
$this->validate($request,[
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if ($data->count() > 0) {
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row) {
$insert_data[] = array(
'kodeBarang' => $row['kode_barang'],
'namaBarang' => $row['nama_barang'],
'stock' => $row['stock'],
'hargaJual' => $row['harga_jual'],
'kategory' => $row['kategory']
);
}
}
if (!empty($insert_data)) {
barang::table('barangs')->insert($insert_data);
}
}
return back()->with('success','berhasil di upload');
}
and i get error message like this
Illegal string offset 'kode_barang'
in barangController.php line 55 at HandleExceptions->handleError(2,
'Illegal string offset \'kode_barang\'',
'C:\xampp\htdocs\penjualan\app\Http\Controllers\barangController.php',
55, array('request' => object(Request), 'path' =>
'C:\xampp\tmp\phpE998.tmp', 'data' => object(RowCollection), 'key'
=> 0, 'value' => array('kode_barang' => 331211, 'nama_barang' => 'coba import', 'stock' => 2, 'harga_jual' => 3000, 'kategory' => 'Minuman',
null), 'row' => 'coba import', 'insert_data' =>
array(array('kodeBarang' => null, 'namaBarang' => null, 'stock' =>
null, 'hargaJual' => null, 'kategory' => null))))
You can solve this issue using the following code.
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row_key => $row) {
$insert_data[] = array(
'kodeBarang' => $row[0],
'namaBarang' => $row[1],
'stock' => $row[2],
'hargaJual' => $row[3],
'kategory' => $row[4]
);
}
}
Add condition to check null row.
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row_key => $row) {
if(!isset($row[0])) {
$insert_data[] = array(
'kodeBarang' => $row[0],
'namaBarang' => $row[1],
'stock' => $row[2],
'hargaJual' => $row[3],
'kategory' => $row[4]
);
}
}
}
Or
foreach ($data->toArray() as $key => $value) {
foreach ($value as $row_key => $row) {
if(!isset($row['kode_barang'])) {
$insert_data[] = array(
'kodeBarang' => $row['kode_barang'],
'namaBarang' => $row['nama_barang'],
'stock' => $row['stock'],
'hargaJual' => $row['harga_jual'],
'kategory' => $row['kategory']
);
}
}
}
Related
I am getting district_id from $allowDistricts array and i want to add filter on Yazra datatable based on $allowDistrict array values.please Look bellow _defaultFilter() function to understand what i want to implement on Yazra datatables
##Code##
$data = DB::table('applications')
->leftJoin('cc_business_type', 'cc_business_type.id', '=','applications.business_type_id')
->leftJoin('divisions', 'divisions.id', '=', 'applications.division_id')
->leftJoin('districts', 'districts.id', '=', 'applications.district_id')
->leftJoin('cc_application_status', 'cc_application_status.id', '=', 'applications.app_present_status_id')
->leftJoin('users', 'users.id', '=', 'applications.app_present_user_id')
->select('applications.id AS id',
'cc_business_type.name_bn AS business_type',
'applications.institution_name AS institution_name',
'divisions.name_bn AS division_name',
'districts.name_bn AS district_name',
'applications.application_date',
'applications.application_type AS application_type',
'applications.challan_amount AS challan_amount',
'applications.plot_holding_no AS plot_holding_no',
'applications.dag_no AS dag_no',
'applications.khatian_no AS khatian_no',
'applications.road_no AS road_no',
'applications.district_id AS district_id',
'applications.app_present_status_id AS app_present_status_id',
'users.full_name AS present_username',
'cc_application_status.name_bn AS present_app_status',
'applications.application_mode AS application_mode'
);
// **$allowDistricts returning district_id array**
**$allowDistricts** = $this->application->getUserAllowedDistricts(Session::get('sess_user_id'));
if(request()->ajax()) {
return \DataTables::of($data)
->filter(function($query) use($allowDistricts){
foreach($allowDistricts as $allowDistrict){
$query->where(.......);
}
})
->addIndexColumn()
->addColumn('button', function($data){
$button = '';
$button .= '<a href="'.route("application/edit",$data->id).'" class="k-button k-grid-edit" id="test" style="min-width: 16px;" title="'.trans('application/breadcrumb1').'" >
'.trans('trans/application.breadcrumb1').'
</a>';
return $button;
})
->rawColumns(['button'])
->make(true);
}
return view('application.list');
Here is defaultfiler function code that i want to implement on my yazra datatables
private function _defaultFilter()
{
$filter = [];
$where = [];
$search = [];
$allowDistricts = $this->application->getUserAllowedDistricts(Session::get('sess_user_id'));
if (!empty($allowDistricts) && is_array($allowDistricts)) {
foreach ($allowDistricts as $allowDistrict) {
$where[] = (object)array(
'field' => 'district_id',
'operator' => 'eq',
'value' => $allowDistrict->district_id
);
}
}
$filter1 = (object)array(
'logic' => 'or',
'filters' => $where);
$search[] = $filter1;
if (Session::get('sess_user_desg_id') == config('app_config.inspector_desg_id')) {
// for inspector
$filter2 = (object)array(
'logic' => 'or',
'filters' => array(
(object)array(
'field' => 'app_present_status_id',
'operator' => 'eq',
'value' => config('app_config.application_status_submit_id')
),
(object)array(
'field' => 'app_present_status_id',
'operator' => 'eq',
'value' => config('app_config.application_status_selected_id')
)
));
$search[] = $filter2;
} else {
// for other than inspector
$filter3 = (object)array(
'logic' => 'and',
'filters' => array(
(object)array(
'field' => 'app_present_status_id',
'operator' => 'neq',
'value' => config('app_config.application_status_approve_id')
),
(object)array(
'field' => 'app_present_status_id',
'operator' => 'neq',
'value' => config('app_config.application_status_reject_id')
),
(object)array(
'field' => 'app_present_status_id',
'operator' => 'neq',
'value' => config('app_config.application_status_draft_id')
)
));
$search[] = $filter3;
}
$filter4 = (object)array(
'logic' => 'and',
'filters' => array(
(object)array(
'field' => 'application_mode',
'operator' => 'eq',
'value' => 'Application'
),
));
$search[] = $filter4;
$filter[] = ['filters' => $search];
return $filter;
}
I want to make an report API with the option of being able to do multiple inputs for violators data, crime scene photo data and personnel data.
I've tried to code like below, but still can't do multiple input. What is the correct way to create multiple inputs in laravel API (with file upload) ?
Controller
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->category_id !== 4 && $request->violator_photo) {
$violators = $request->file('violator_photo');
$violators = [];
foreach($violators as $key => $value) {
if($request->hasFile('violator_photo')) {
$violator_photo = $request->hasFile('violator_photo');
$fileName = time().'_'.$violator_photo[$key]->getClientOriginalName();
$filePath = $violator_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
}
$data = new Violator();
$data->report_id = $report->id;
$data->name = $request->violator_name[$key];
$data->photo = $filePath[$key];
$data->age = $request->violator_age[$key];
$data->phone = $request->violator_phone[$key];
$data->save();
}
}
$files = $request->file('crime_scene_photo');
$files = [];
foreach($files as $key => $value) {
if($request->hasFile('crime_scene_photo')) {
$crime_scene_photo = $request->hasFile('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
}
$data = new CrimeScenePhoto();
$data->report_id = $report->id;
$data->path = $path[$key];
$data->caption = $request->caption[$key];
$data->save();
}
if (\Auth::user()->unit_id == 2 && $request->personel) {
foreach ($request->personel as $key => $value) {
$report->members()->sync($request->personel[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report,
$request->all()
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
And here is how I tested in postman.
Solved. i changed my code to like this and it work.
public function store(ReportRequest $request)
{
try {
$report = Report::create([
'category_id' => $request->category_id,
'user_id' => Auth::user()->id,
'title' => $request->title,
'description' => $request->description,
'incident_date' => $request->incident_date,
'injured_victims' => $request->injured_victims,
'survivors' => $request->survivors,
'dead_victims' => $request->dead_victims,
'location' => $request->location,
'latitude' => $request->latitude,
'longitude' => $request->longitude
]);
if ($request->hasFile('violator_photo')) {
foreach($request->file('violator_photo') as $key => $value) {
$vio_photo = $request->file('crime_scene_photo');
$fileName = time().'_'.$vio_photo[$key]->getClientOriginalName();
$filePath = $vio_photo[$key]->storeAs('images/pelanggar', $fileName, 'public');
Violator::create([
'report_id' => $report->id,
'name' => $request->violator_name[$key] ?? null,
'photo' => $filePath ?? null,
'age' => $request->violator_age[$key] ?? null,
'phone' => $request->violator_phone[$key] ?? null
]);
}
}
if ($request->hasFile('crime_scene_photo')) {
foreach($request->file('crime_scene_photo') as $key => $value) {
$crime_scene_photo = $request->file('crime_scene_photo');
$name = time().'_'.$crime_scene_photo[$key]->getClientOriginalName();
$path = $crime_scene_photo[$key]->storeAs('images/tkp', $name, 'public');
CrimeScenePhoto::create([
'report_id' => $report->id,
'path' => $path ?? null,
'caption' => $request->caption[$key] ?? null
]);
}
}
if (\Auth::user()->unit_id == 2 && $request->personel_id) {
foreach ($request->personel_id as $key => $value) {
$report->members()->attach($request->personel_id[$key]);
}
}
return response()->json([
'status' => '200',
'message' => 'success',
'data' => [
$report, $report->members, $report->violators, $report->photos
],
]);
} catch (\Exception$err) {
return $this->respondInternalError([$err->getMessage(), $request->all()]);
}
}
I save image in database as array ["product-04.jpg"]. I don't know how to display image to view. I used Crinsane/LaravelShoppingcart and got the following error: "Cannot use object of type Gloudemans\Shoppingcart\CartItem as array". Can everyone help me?
ProductController I saved image in db:
if($request->hasFile('images')){
$files = $request->file('images');
$extension = ['png','jpg','gif','jepg'];
foreach ($files as $key => $item) {
$nameFile = $item->getClientOriginalName();
$exFiles = $item->getClientOriginalExtension();
if(in_array($exFiles, $extension)){
$item->move(public_path().'/upload/images',$nameFile);
$arrNameFile[] = $nameFile;
}
}
}
if($arrNameFile){
$dataInsert = [
'name_product' => $nameProduct,
'categories_id' => json_encode($categories),
'colors_id' => json_encode($colors),
'sizes_id' => json_encode($sizes),
'brands_id' => $brand,
'price' => $price,
'qty' => $qty,
'description' => $description,
'image_product' => json_encode($arrNameFile),
'sale_off' => $sale,
'status' => 1,
'view_product' => 0,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => null
];
if($pd->addDataProduct($dataInsert)){
$request->session()->flash('addPd','success');
return redirect()->route('admin.products');
} else {
$request->session()->flash('addPd','Fail');
return redirect()->route('admin.addProduct');
}
} else {
$request->session()->flash('addPd','Can not upload image');
return redirect()->route('admin.addProduct');
}
}
CartController: I add products and want to show list products in cart
public function addCart(Request $request, $id)
{
$product = Products::select('name_product', 'id', 'price', 'qty', 'image_product')->find($id);
if(!$product) return redirect('/');
Cart::add([
'id' => $id,
'name' => $product->name_product,
'qty' => 1,
'price' => $product->price,
'options' => [
'images' => json_decode($product->image_product, true),
]
]);
return redirect()->back();
}
public function getListCart(){
$products = Cart::content();
return view('frontend.cart.showCart', compact('products'));
}
And view i get image in src : {{ URL::to('/') }}/upload/images/{{ $product->image_product[0] }}
I'm trying to import an excel to my database table 'users' but it has an error saying Illegal string offset "email". I tried deleting the "email" then it says that Illegal string offset "username" now. Is it really the error in controller? Or maybe the reason is that i also have a repository.
This is my code for the controller
public function userImport()
{
if( Input::file('file_import') ) {
$path = Input::file('file_import')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
}
});
}
if (!empty($inserts)) {
DB::table('users')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
As per your dumped $rows, it looks like that you don't need another foreach inside another foreach, modify your code.
// readability purpose
$rows = $reader->toArray();
foreach ($rows as $row){
$inserts[] = ['email' => $row['email'], 'username' => $row
['username'], 'password' => $row['password'], 'first_name' => $row['first_name'],'middle_name' => $row['middle_name'], 'last_name' => $row['last_name'], 'gender' => $row['gender'],
'civil_status' => $row['civil_status'], 'spouse' => $row['spouse'], 'religion' => $row['religion'],'emergency_no' => $row['emergency_no'],'previous_work' => $row['previous_work'],
'remarks' => $row['remarks'],'course' => $row['course'],'biometrics' => $row['biometrics'],'immediate_head' => $row['immediate_head'],'designation' => $row['designation'],'level' => $row['level'],
'emp_status' => $row['emp_status'],'dependents' => $row['dependents'],'date_hired' => $row['date_hired'],'regularization_date' => $row['regularization_date'],'remmitance_date' => $row['remmitance_date'],
'tin' => $row['tin'],'philhealth' => $row['philhealth'],'pagibig' => $row['pagibig'],'sss' => $row['sss'],'umid' => $row['umid'],'phone' => $row['phone'],'avatar' => $row['avatar'],
'address' => $row['address'],'country_id' => $row['country_id'],'role_id' => $row['role_id'],'birthday' => $row['birthday'],'status' => $row['status']];
}
$rows already represents each row, so you should probably rename it to $row.
I'm working on some e-commerce website based on merchant. There is problem comping in submitting order. the problem is when i'm selecting same merchant that time order will be stored successfully, but when i'm selecting multiple product from different merchant that time my function through error of Undefined offset:1. Here is my function.
public function post_order(){
$data = Input::all();
$count = count($data['invoice_no']);
$order = array();
for($i=0; $i<$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($order, array(
'order_no' => $data['order_no'][$i],
'invoice_prefix' => $data['invoice_prefix'][$i],
'invoice_no' => $data['invoice_no'][$i],
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'buytokri_order' => $data['order_name'][$i],
'name' => $data['name'][$i],
'pincode' => $data['pincode'][$i],
'address' => $data['address'][$i],
'landmark' => $data['landmark'][$i],
'city' => $data['city'][$i],
'state' => $data['state'][$i],
'country' => $data['country'][$i],
'mobile' => $data['mobile'][$i],
'subtotal' => $data['selling_price'][$i],
'payment_type' => $data['payment_type'][$i],
'txn_id' => $data['txn'][$i],
'shipping' => $data['shipping'][$i],
'total' => $data['subtotal'][$i]
));
}
}
Order::insert($order);
$var = $data['order_no'];
foreach ($var as $vars) {
$id = DB::table('ads_order')->where('order_no', $vars)->get();
}
$count = count($data['invoice_no']);
$orderhistory = array();
for($i=0; $i<=$count; $i++){
if(!empty($data['invoice_no'][$i])){
array_push($orderhistory, array(
'order_id' => $id[$i]->id,
'merchant_id' => $data['merchant_id'][$i],
'customer_id' => $data['customer_id'][$i],
'order_status' => $data['order_status'][$i],
'comment' => $data['comment'][$i],
'notify' => $data['notify'][$i],
'default' => $data['default'][$i],
'status' => $data['status'][$i]
));
}
}
Orderhistory::insert($orderhistory);
return Redirect::intended('/ordersuccess');
}