Laravel5.3 maatwebsite/excel Read value from excel & insert into database - laravel

Here is my Excel data sheet type:
Here is My Table Schema:
Here is my method to import data:
public function saveActivationInfoExcel(Request $request)
{
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = [
'mobile_no' =>$v['mobile_no'],
'model' => $v['model'],
'serial_1' => $v['serial_1'],
'serial_2' => $v['serial_2'],
'activation_date' => $v['activation_date'],
];
}
}
}
dd($insert);
if(!empty($insert)){
//ProductActivationInfo::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}
}
return back()->with('error','Please Check your file, Something is wrong there.');
}
Now my problem is, when I try to import data I got this dd($insert) error
Illegal string offset 'mobile_no'
'serial_1' => '3.5194508009307E+14',
'serial_2' => '3.5194508009307E+14',
'activation_date' => object(Carbon), null)
have a look both serial_1 & serial_2 showing different value rather then actual excel value. also activation_date value is null.
would appreciate your valuable suggestion to solve this regarding reading data using "maatwebsite/excel" laravel library.

Please use the CSV file to import data and change the serial_1 and serial_2 column format as a fraction. And change the format of activation_date column.
Thanks

Related

CodeIgniter 3 code does not add data to database into 2 different tables (user_info & phone_info)

The problem is when I entered a new name no data is added. A similar thing happen when I entered an already existing name. Still, no data is added to the database. I am still new to CodeIgniter and not entirely sure my query builder inside the model is correct or not.
In the Model, I check if the name already exists insert data only into the phone_info table. IF name does not exist I insert data into user_info and phone_info.
Controller:
public function addData()
{
$name = $this->input->post('name');
$contact_num = $this->input->post('contact_num');
if($name == '') {
$result['message'] = "Please enter contact name";
} elseif($contact_num == '') {
$result['message'] = "Please enter contact number";
} else {
$result['message'] = "";
$data = array(
'name' => $name,
'contact_num' => $contact_num
);
$this->m->addData($data);
}
echo json_encode($result);
}
Model:
public function addData($data)
{
if(mysqli_num_rows($data['name']) > 0) {
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info',$phone_info);
} else {
$user_info = array(
'name' => $data['name']
);
$this->db->insert('user_info', $user_info);
$user = $this->db->get_where('user_info', array('name' => $data['name']))->result_array();
$user_id = $user['id'];
$phone_info = array(
'contact_num' => $data['contact_num'],
'user_id' => $user_id
);
$this->db->insert('phone_info', $phone_info);
}
}
DB-Table user_info:
DB-Table phone_info:
Extend and change your model to this:
public function findByTitle($name)
{
$this->db->where('name', $name);
return $this->result();
}
public function addData($data)
{
if(count($this->findByTitle($data['name'])) > 0) {
//.. your code
} else {
//.. your code
}
}
Explanation:
This:
if(mysqli_num_rows($data['name']) > 0)
..is not working to find database entries by name. To do this you can use codeigniters built in model functions and benefit from the MVC Pattern features, that CodeIgniter comes with.
I wrapped the actual findByName in a function so you can adapt this to other logic and use it elswehere later on. This function uses the query() method.
Read more about CodeIgniters Model Queries in the documentation.
Sidenote: mysqli_num_rows is used to iterate find results recieved by mysqli_query. This is very basic sql querying and you do not need that in a MVC-Framework like CodeIgniter. If you every appear to need write a manual sql-query, even then you should use CodeIgniters RawQuery methods.

Make request (pass data) from Command File to Controller in Lumen/Laravel

i get data (query) in command file and want to pass to controller via API (route)
here my request code in command file :
$request = Request::create('/create_data_account', 'post', ['data'=>$data]);
$create = $app->dispatch($request);
this is the route :
$router->post('/create_data_account', 'APIController#create_account_data_api');
and my controller :
public function create_account_data_api(Request $request)
{
$count = 0;
foreach ($data as $key => $value) {
$insert = Account::create([
'account_name' => $value->account_name,
'type' => $value->type,
'role_id' => $value->role_id
]);
if($insert){
$count++;
}else{
return $response = ['result'=>false, 'count'=>$count, 'message'=>'Internal error. Failed to save data.'];
}
}
return $response = ['result'=>true, 'count'=>$count, 'message'=>'Account data saved Successfully'];
}
i'm confused why passing data to controller not working with that code. anyone can give me solution ? Thanks
As you are making the request with ['data'=>$data]. That means all the data is contained on the key data of your array. So before the foreach loop, you need to add a declaration statement $data = $request->input('data'); to get data in $data variable.

update table with csv using laravel

I'm trying to update a table using Maatwebsite/Laravel-Excel.
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader)
{
})->get();
if(!empty($data) && $data->count())
{
foreach ($data->toArray() as $row)
{
if(!empty($row))
{
$dataArray[] =
[
//'name' => $row['name'],
'age' => $row['age'],
'phone' => $row['phone'],
//'created_at' => $row['created_at']
];
}
if(!empty($dataArray))
{
//Item::insert($dataArray);
DB::table('items')
->where('name', $row['name'])->update($dataArray);
return view('imported')->with('success', 'Course updated');
}
}
}
}
}
But its giving error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update items set 0 = 20 where name = james
Here's my csv
name,age,phone
James,20,888839939
Joseph,54,3444444
Hanson,30,99999999
The above is the csv file i'm trying to update.
The problem is that $dataArray is an array of arrays, so to make it work you have to loop each one:
if(!empty($dataArray)) {
foreach ($dataArray as $array) {
DB::table('items')
->where('name', $row['name'])
->update($array);
}
return view('imported')->with('success', 'Course updated');
}
But this wouldn't make much sense, because every time it would be updating the row with name = $row['name'], so you probbaly need to update the line where you set a value to the $dataArray from $dataArray[] = ... to $dataArray = ...*, so it could have a single value.
In case any body comes across this, this is how i solved it.
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
Excel::load($path)->each(function (Collection $csvLine) {
DB::table('items')
->where('id', $csvLine->get('id'))
->update(['name' => $csvLine->get('name'),'phone' => $csvLine->get('phone'),'age' => $csvLine->get('age')]);
});
return view('imported')->with('success', 'Course updated');
}
}
I used the each() collection method to loop through the csv file and it won the battle.

Laravel Excel - Select columns to export

I'm using Laravel Excel from maatwebsite but i have a problem with export data to xls file. I have this query but i don't need to show all columns in the xls file but i need to select all this columns to do operations before download the file. In my select i have 8 columns but in my headers i just have 7 to show but this doesn't work because the 8ª column appears too.
MY FUNCTION:
public function toExcel($id) { $b = Budget::find($id);
$budget = Budget_Item::join('budgets', 'budget__items.id_budget', '=', 'budgets.id')
->join('items_sizes', 'budget__items.id_itemSize', '=', 'items_sizes.id')
->join('items', 'items_sizes.id_item', '=', 'items.id')
->join('material_types', 'items_sizes.id_materialType', '=', 'material_types.id')
->select('items.reference AS Referência', 'items.name AS Descrição', 'items_sizes.size AS Tamanho', 'material_types.material_type AS Material', 'budget__items.amount AS Quantidade', 'items_sizes.unit_price AS Val.Unitário', 'budget__items.price AS Val.Total', 'budget__items.purchasePrice')
->where('id_budget', '=', $id)
->get();
$budgetUpdate = [];
$budgetUpdate[] = ['Referência', 'Descrição', 'Tamanho', 'Material', 'Quantidade', 'Val.Unitário', 'Val.Total'];
foreach ($budget as $key)
{
if ($key->purchasePrice > 0)
{
$key->unit_price = $key->purchasePrice;
}
$budgetUpdated[] = $key->toArray();
}
Excel::create('Proposta_'.$b->reference, function($excel) use($budgetUpdated)
{
// Set the title
$excel->setTitle('Proposta');
$excel->sheet('Sheetname', function($sheet) use($budgetUpdated)
{
$sheet->fromArray($budgetUpdated, null, 'A1', false, true);
});
})->download('xls');}
How can i solve that?
Thank's
Tested on Laravel excel 3.1 docs
on controller
public function exportAsCsv()
{
return Excel::download(new MyExport, 'invoices.xlsx');
}
on MyExport, look at the map function
class MyExport implements FromCollection, WithHeadings, WithMapping{
public function collection(){
return MyTable:all();
}
// here you select the row that you want in the file
public function map($row): array{
$fields = [
$row->myfield2,
$row->myfield1,
];
return fields;
}
}
also check this
For what its worth I ran into a similar issue and didnt find much in terms of a fix so heres my solution.
1. I query the DB in the callback and get all the data I need.
2. I then go over the collection and create a new array on each iteration and assign a value & header. Works great for picking out columns from a model
Excel::create('User List Export', function($excel) {
$excel->sheet('Users', function($sheet) {
$email = yourModelGoesHere::all();
foreach ($email as $key => $value) {
$payload[] = array('email' => $value['email'], 'name' => $value['name']);
}
$sheet->fromArray($payload);
});
})->download('xls');
You can try this way.
$user_id = Auth::user()->id
Excel::create('User', function($excel) use ($user_id){
$excel->sheet('Sheet', function($sheet) use($user_id){
$user = User::where('user_id', $user_id)->select('name', 'email', 'role', 'address')->get();
});
})->export('xls');
return redirect('your route');

CodeIgniter ActiveRecord problems

I'm trying to build my first app on CodeIgniter. This is also my first time trying to stick to OOP and MVC as much as possible. It's been going ok so far but now that I'm trying to write my first model I'm having some troubles. Here's the error I'm getting:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Castledine' at line 3
SELECT * FROM (authors) WHERE author = Earle Castledine
Which, as you'll see below, relates to the following line in my model:
$this->db->get_where('authors', array('author' => $author));
I'm not quite sure why it's throwing the error. Is it because Earle Castledine isn't in quotes? If so, why doesn't CI put them in there? I would doubt that's the issue, rather to think it's my fault, but I'm not sure.
I'm having another issue as well. Neither tags nor authors are getting inserted into their respective tables. Their insert statement is wrapped in a conditional that's supposed to be making sure they don't already exist, but it seems to be failing and the insert never happens. I assume it's failing because the tags aren't getting put in the database and it's down in the author section before it tosses the error. I know how to do this with pure PHP but I'm trying to go about doing it the pure CI ActiveRecord way.
Here's the statement I'm using:
if ($this->db->count_all_results() == 0)
And I'm using that instead of what I'd normally use:
if (mysql_num_rows() == 0)
Am I doing it wrong?
Here are my model and controller (only the functions that matter), commented as best I could.
Model:
function new_book($book, $tags, $authors, $read) {
// Write book details to books table
$this->db->insert('books', $book);
// Write tags to tag table and set junction
foreach ($tags as $tag) {
// Check to see if the tag is already in the 'tags' table
$this->db->get_where('tags', array('tag' => $tag));
// trying to use this like mysql_num_rows()
if ($this->db->count_all_results() == 0) {
// Put it there
$this->db->insert('tags', $tag);
}
// Set the junction
// I only need the id, so...
$this->db->select('id');
// SELECT id FROM tags WHERE tag = $tag
$query = $this->db->get_where('tags', array('tag' => $tag));
// INSERT INTO books_tags (book_id, tag_id) VALUES ($book['isbn'], $query->id)
$this->db->insert('books_tags', array('book_id' => $book['isbn'], 'tag_id' => $query->id));
}
// Write authors to author table and set junction
// Same internal comments apply from tags above
foreach ($authors as $author) {
$this->db->get_where('authors', array('author' => $author));
if ($this->db->count_all_results() == 0) {
$this->db->insert('authors', $author);
}
$this->db->select('id');
$query = $this->db->get_where('authors', array('author' => $author));
$this->db->insert('authors_books', array('book_id' => $book['isbn'], 'author_id' => $query));
}
// If the user checked that they've read the book
if (!empty($read)) {
// Get their user id
$user = $this->ion_auth->get_user();
// INSERT INTO books_users (book_id, tag_id) VALUES ($book['isbn'], $user->id)
$this->db->insert('books_users', array('book_id' => $book['isbn'], 'user_id' => $user->id));
}
}
Controller:
function confirm() {
// Make sure they got here by form result, send 'em packing if not
$submit = $this->input->post('details');
if (empty($submit)) {
redirect('add');
}
// Set up form validation
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h3 class="error">', ' Also, you’ll need to choose your file again.</h3>');
$this->form_validation->set_rules('isbn','ISBN-10','trim|required|exact_length[10]|alpha_numeric|unique[books.isbn]');
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('tags','tags','required');
// Set up upload
$config['upload_path'] = './books/';
$config['allowed_types'] = 'pdf|chm';
$this->load->library('upload', $config);
// If they failed validation or couldn't upload the file
if ($this->form_validation->run() == FALSE || $this->upload->do_upload('file') == FALSE) {
// Get the book from Amazon
$bookSearch = new Amazon();
try {
$amazon = $bookSearch->getItemByAsin($this->input->post('isbn'));
} catch (Exception $e) {
echo $e->getMessage();
}
// Send them back to the form
$data['image'] = $amazon->Items->Item->LargeImage->URL;
$data['content'] = 'add/details';
$data['error'] = $this->upload->display_errors('<h3 class="error">','</h3>');
$this->load->view('global/template', $data);
// If they did everything right
} else {
// Get the book from Amazon
$bookSearch = new Amazon();
try {
$amazon = $bookSearch->getItemByAsin($this->input->post('isbn'));
} catch (Exception $e) {
echo $e->getMessage();
}
// Grab the file info
$file = $this->upload->data();
// Prep the data for the books table
$book = array(
'isbn' => $this->input->post('isbn'),
'title' => mysql_real_escape_string($this->input->post('title')),
'date' => $amazon->Items->Item->ItemAttributes->PublicationDate,
'publisher' => mysql_real_escape_string($amazon->Items->Item->ItemAttributes->Publisher),
'pages' => $amazon->Items->Item->ItemAttributes->NumberOfPages,
'review' => mysql_real_escape_string($amazon->Items->Item->EditorialReviews->EditorialReview->Content),
'image' => mysql_real_escape_string($amazon->Items->Item->LargeImage->URL),
'thumb' => mysql_real_escape_string($amazon->Items->Item->SmallImage->URL),
'filename' => $file['file_name']
);
// Get the tags, explode by comma or space
$tags = preg_split("/[\s,]+/", $this->input->post('tags'));
// Get the authors
$authors = array();
foreach ($amazon->Items->Item->ItemAttributes->Author as $author) {
array_push($authors, $author);
}
// Find out whether they've read it
$read = $this->input->post('read');
// Send it up to the database
$this->load->model('add_model', 'add');
$this->add->new_book($book, $tags, $authors, $read);
// For now... Later I'll load a view
echo 'Success';
}
}
Could anyone help shed light on what I'm doing wrong? Thanks much.
Marcus
Where you are using count_all_results(), I think you mean to use num_rows(). count_all_results() will actually create a SELECT COUNT(*) query.
For debugging your problems...
If you want to test if an insert() worked, use affected_rows(), example:
var_dump($this->db->affected_rows());
At any point you can output what the last query with last_query(), example:
var_dump($this->db->last_query());
You can also turn on the Profiler so you can see all the queries being run, by adding in the controller:
$this->output->enable_profiler(TRUE);
I managed to figure this out on my own. The controller didn't really change, but here's the new model:
function new_book($book, $tags, $authors, $read) {
// Write book details to books table
$this->db->insert('books', $book);
// Write tags to tag table and set junction
foreach ($tags as $tag) {
// Check to see if the tag is already in the 'tags' table
$query = $this->db->get_where('tags', array('tag' => $tag));
// trying to use this like mysql_num_rows()
if ($query->num_rows() == 0) {
// Put it there
$this->db->insert('tags', array('tag' => $tag));
}
// Set the junction
// I only need the id, so...
$this->db->select('id');
// SELECT id FROM tags WHERE tag = $tag
$query = $this->db->get_where('tags', array('tag' => $tag));
$result = $query->row();
// INSERT INTO books_tags (book_id, tag_id) VALUES ($book['isbn'], $query->id)
$this->db->insert('books_tags', array('book_id' => $book['isbn'], 'tag_id' => $result->id));
}
// Write authors to author table and set junction
// Same internal comments apply from tags above
foreach ($authors as $author) {
$query = $this->db->get_where('authors', array('author' => mysql_real_escape_string($author)));
if ($query->num_rows() == 0) {
$this->db->insert('authors', array('author' => mysql_real_escape_string($author)));
}
$this->db->select('id');
$query = $this->db->get_where('authors', array('author' => mysql_real_escape_string($author)));
$result = $query->row();
$this->db->insert('authors_books', array('book_id' => $book['isbn'], 'author_id' => $result->id));
}
// If the user checked that they've read the book
if (!empty($read)) {
// Get their user id
$user = $this->ion_auth->get_user();
// INSERT INTO books_users (book_id, tag_id) VALUES ($book['isbn'], $user->id)
$this->db->insert('books_users', array('book_id' => $book['isbn'], 'user_id' => $user->id));
}
}

Resources