Save data in db from excel in laravel - php

I need to import excel data in db. but is giving me tough time.
here is my controller function
$path = Input::file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['product_id' => $value->price, 'details' =>
$value->stock];
}
if(!empty($arr)){
\DB::table('stock')->insert($arr);
dd('Insert Record successfully.');
}
}
where price and stock is fields in excel.
below is the error
Property [price] does not exist on this collection instance.
here is dd() of my controller function when i am trying to save excel data in db.
SheetCollection {#375 ▼
#title: ""
#items: array:3 [▼
0 => RowCollection {#498 ▼
#heading: array:2 [▼
0 => "stock"
1 => "price"
]
#title: "Sheet1"
#items: array:3 [▼
0 => CellCollection {#462 ▼
#title: null
#items: array:2 [▼
"stock" => 2.0
"price" => 3.0
]
}
1 => CellCollection {#481 ▼
#title: null
#items: array:2 [▼
"stock" => 3.0
"price" => 2.0
]
}
2 => CellCollection {#480 ▼
#title: null
#items: array:2 [▶]
}
]
}
1 => RowCollection {#533 ▶}

I'll paste my import function here, modify them for your needs.
My excel template has only 1 sheet and the first row contains the field names.
// Retrieve file
$file = $request->file('file');
$ext = $file->getClientOriginalExtension();
// Just my helper method to create filenames
$filename = Helper::create_filename($ext);
// Move file
$path ="uploads/import";
$file->move($path, $filename);
Excel::selectSheetsByIndex(0)->load("{path}/{$filename}", function($reader) {
$sheet = $reader->all();
foreach ($sheet as $i => $row) {
$data = $row->toArray(); // Utilize this data to fill your model
}
});

CHANGE EXCEL SHEET COLUMN NAME LIKE THAT
price stock
100 400
200 15
12 167

Related

Laravel Object of class stdClass could not be converted to string. Still object when using toArray();

I have a table that I want to export via excel. I use the method toArray(); and still I get the result as object. Here is my sample code
$items = \DB::table('users')
->join('finances', 'users.id','=','finances.user_id')
->join('schoolyears', 'users.school_id','=','schoolyears.school_id')
->select('users.name','users.phone','users.section_id', 'users.student_school_id','finances.amount','finances.description','schoolyears.name as syear','finances.date')
->where('finances.date', '=' ,(\DB::raw("(select max(`date`) from finances f where finances.user_id=f.user_id)")))
->where('users.role','=','4' )
->where('users.school_id','=', $sid)
->get()->toArray();
// dd($items);
} else {
return redirect('home')->with('error', 'Invalid access');
}
\Excel::create($this->page_title . 's', function ($excel) use ($items) {
$excel->sheet($this->page_title . 's', function ($sheet) use ($items) {
$sheet->fromArray($items);
});
The result I get when i dd($items)
array:2 [▼
0 => {#558 ▼
+"name": "Annamarie Morar"
+"phone": "(0997) 212-7919"
+"section_id": null
+"student_school_id": "50"
+"amount": "500"
+"description": "New Pays"
+"syear": "SY-2019-2020"
+"date": "2019-11-14"
}
1 => {#561 ▶}
]
What i want is like this so that i can export it as an excel file
array:9 [▼
0 => array:10 [▼
"FirstName" => "Madelynn"
"LastName" => "Stokes"
"Gender" => "female"
"Birthday" => "2013-10-09"
"Address" => "78A/40 Goodwin Meadow, Poblacion, Iloilo City 1333 Nueva Ecija"
"PhoneNo" => "+63 (971) 659-8143"
"Parent" => "Deondre Stokes"
"SchoolID" => "521"
"RFID" => "173"
"Section" => null
]
1 => array:10 [▶]
2 => array:10 [▶]
3 => array:10 [▶]
4 => array:10 [▶]
5 => array:10 [▶]
6 => array:10 [▶]
7 => array:10 [▶]
8 => array:10 [▶]
]
You could convert each object to an array by transforming the Collection then turning the Collection into an array if you had to:
$items = DB::table(...)->.....->get()->transform(function ($item) {
return (array) $item;
})->toArray();
Laravel 6.x Docs - Collections - Methods - transform

Array_merge in laravel

I have data I return them into collection but it does not return as i wish and i need help to fix it.
output
array:11 [▼
0 => Collection {#2762 ▼
#items: array:3 [▼
0 => Product {#2758 ▶}
1 => Product {#2759 ▶}
2 => Product {#2760 ▶}
]
}
1 => Collection {#2792 ▼
#items: []
}
2 => Collection {#2948 ▼
#items: []
}
3 => Collection {#3102 ▼
#items: []
}
4 => Collection {#3216 ▼
#items: []
}
5 => Collection {#2886 ▼
#items: array:10 [▶]
}
6 => Collection {#2920 ▼
#items: array:3 [▶]
}
7 => Collection {#3046 ▼
#items: array:12 [▶]
}
8 => Collection {#3074 ▼
#items: []
}
9 => Collection {#3188 ▼
#items: array:7 [▶]
}
10 => Collection {#3288 ▼
#items: []
}
]
Code
$category = Category::where('slug','=',$catslug)->with('childs', 'parent')->first();
$pp1[] = Product::where('category_id',$category->id)->get();
foreach($category->childs as $first){
$pp2[] = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3[] = Product::where('category_id',$second->id)->get();
}
}
}
$products = array_merge($pp1,$pp2,$pp3);
dd($products);
What it should return
It should return all products from all arrays in 1 array only and not categorized by Collection {#2792 ▼ I need to get only collections with items and not the ones that are empty.
Any idea?
update
I've also tried this:
$pp1 = [];
$pp2 = [];
$pp3 = [];
$pp1 = Product::where('category_id',$category->id)->get();
foreach($category->childs as $first){
$pp2 = Product::where('category_id',$first->id)->get();
if(count($first->childs)> 0){
foreach($first->childs as $second){
$pp3 = Product::where('category_id',$second->id)->get();
}
}
}
it returns:
array_merge(): Argument #1 is not an array
You can get all products of the category, of its children and of its grand-children as,
$category = Category::where('slug','=',$catslug)
->with([
'products',
'childs.products',
'childs.childs.products',
'parent'
])
->first()
->toArray();
$products = array_merge([
data_get($category, 'products'),
array_collapse(data_get($category, 'childs.*.products')),
array_collapse(data_get($category, 'childs.*.childs.*.products'))
]);
Fiddle : https://implode.io/ebXrD8

How to retrieve nested array data in PHP/Laravel?

{`
+"insights": array:1 [▼
0 => {#209 ▼
+"group": "Provision"
+"dataset": array:1 [▼
0 => {#207 ▼
+"group": "Provision"
+"set": array:3 [▼
0 => {#194 ▼
+"name": "Neutral"
+"value": 917
}
1 => {#203 ▶}
2 => {#197 ▶}
]
}
]
}
]
+"errorCode": 0
}`
How to get the name property inside the set array? I've tried multiple way but it kept error return trying to get property non-object.
suppose you provide $response to your blade view
$response = {
+"insights": array:1 [▼
0 => {#209 ▼
+"group": "Provision"
+"dataset": array:1 [▼
0 => {#207 ▼
+"group": "Provision"
+"set": array:3 [▼
0 => {#194 ▼
+"name": "Neutral"
+"value": 917
}
1 => {#203 ▶}
2 => {#197 ▶}
]
}
]
}
]
+"errorCode": 0
}
You have to loop through to response , in your blade view :
#foreach($response->insights as $insight)
#foreach($insight['dataset'] as $dataset)
#foreach($dataset['set'] as $set)
<tr><td>$set['name']</td></tr>
#endforeach
#endforeach
#endforeach
data_get($data, 'insights.0.dataset.0.set.0.name');
end if you have json - convert it into array -> json_decode(string);
You have to simply loop through it and do whatever you want to with that name,
foreach($response->insights as $temp){
foreach($temp->dataset as $var){
foreach($var as $obj){
$name = $obj->name;
}
}
}

Why my structure of collection is not expected (not as I need)

I have the following method of my cart class:
public function add($productId) {
$product = Product::where('id', $productId)->first();
if (!$product) {
return false;
}
if ($this->items->has($productId)) {
$this->items->$productId->qty++;
} else {
$this->items->push([$productId => [
'name' => $product->title,
'price' => $product->price,
'is_sale' => $product->is_sale,
'sale_price' => $product->sale_price,
'sale_percent' => $product->sale_percent,
'can_use_promocode' => $product->can_use_promocode,
'qty' => 1,
]
]);
}
$this->save();
return true;
}
But on dump($cart) in controller, I got this:
+items: Collection {#176 ▼
#items: array:1 [▼
0 => {#171 ▼
+"2": {#164 ▼
+"name": "101 роза"
+"price": 4999
+"is_sale": 0
+"sale_price": null
+"sale_percent": null
+"can_use_promocode": 1
+"qty": 1
}
}
]
}
But I need to:
+items: Collection {#176 ▼
#items: array:1 [▼
2 => {
+"name": "101 роза"
+"price": 4999
+"is_sale": 0
+"sale_price": null
+"sale_percent": null
+"can_use_promocode": 1
+"qty": 1
}
]
}
In this case, I thought that $this->items->push([$productId => ...] will push the key => value pair to collection, but collection creates its own pair, and my pair goes into collection pair. (idk how to describe it correctly, but I think you understand me :) )
Use the put() method instead:
->put($key, $data)
The put method sets the given key and value in the collection

How to array_values laravel collection?

I have a search result from image model and $photo saved the data which $photo->type == 'photo'.
$photo = $image->filter(function($photo,$key) use($path){
if($photo->type == 'photo'){
$photo->url = $path.$photo->image;
return $photo;
}
});
Here is the $photo collection and is there any way to array_values() the items data?
Collection {#352 ▼
#items: array:3 [▼
2 => ImageBanquet {#349 ▶}
3 => ImageBanquet {#350 ▶}
4 => ImageBanquet {#351 ▶}
]
}
Check values() collection helper.
$values = $collection->values();

Categories