Trying to figure out why I am getting the following error:
Undefined index Plugin ID
I am using Maatwebsite\Excel for my import and tried using the guide here:
https://appdividend.com/2017/06/12/import-export-data-csv-excel-laravel-5-4/
I think I have everything in the right place, but I am getting the above error from this code:
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[] =
[
'plugin_id' => $row['Plugin ID'],
'cve' => $row['CVE'],
'cvss' => $row['CVSS'],
'risk' => $row['Risk'],
'host' => $row['Host'],
'protocol' => $row['Protocol'],
'port' => $row['Port'],
'name' => $row['Name'],
'synopsis' => $row['Synopsis'],
'description' => $row['Description'],
'solution' => $row['Solution'],
'see_also' => $row['See Also'],
'plugino_utput' => $row['Plugin Output']
];
}
}
if(!empty($dataArray))
{
Shipping::insert($dataArray);
return back();
}
}
}
}
This is in my controller file and is trying to account for the headers being different in the CSV compared to in my database.
Any idea why it would be complaining about index on a column from the csv side of things?
I ended up with this for now from another post. The post still had an extra section in it, but doing a var_dump on $value (which I left in, but commented out) I could see that $value was already an array, so instead of passing it into another array, I tried just inserting with it and that seems to be working.
Still working on placing the error and success messages.
Thanks to ljubadr for helping me learning how to put some print type statements in with the code to see what was getting output at various places.
public function importExcel(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)){
#var_dump($value);
Item::insert($value);
}
}
return back()->with('success','Insert Record successfully.');
}
}
#return back()->with('error','Please Check your file, Something is wrong there.');
}
}
Related
I use Maatwebsite/Laravel-Excel package to upload CSV to DB. Before entering data to DB i wanna do some additional checks with the database. Something like Project_id available in the Project table. Where do i write the required checking function. Is it a proper way to write it in the same controller. I have seen some people create folder In app\Example and write function file in it
UPDATE :
please let me know is this a proper way to do
https://www.youtube.com/watch?v=fS8q_sD1sZM
This the sample CSV format
This the controller function
public function uploadDealerCSV()
{
if(Input::hasFile('file')){
$path = Input::file('file')->getRealPath();
$data = Excel::load($path, function ($reader) {
$reader->ignoreEmpty();
})->get();
if(!empty($data) && $data->count()){
foreach ($data as $key => $value) {
$insert[] = [
'project_id' => $value->project_id,
'dealer_bl_code' => $value->bl_code,
'reporgroup' => 104,
'added_by' => 73,
'updated_at' => '2017-08-08 10:34:54',
];
}
if(!empty($insert)){
DB::table('cts_project_list')->insert($insert);
//dd('Insert Record successfully.');
}
}
}
return back();
}
public function testFunction(){
}
I'm trying to update my products with dynamic variants. There is no issue in adding or deleting but when I trying to update, every time it updates with the last record on every field.
I'm trying to update dynamic variants where I have inserted...
color - red
shape -square
It's about dynamic form-fields, inserts work properly but when I am trying to update it, it updates the first value with both the filled and the second value with both the field and I won't be able to distinguish the field because of the Blade file returns in form of an array.
When I am trying to update with any value it repeats the last value in both the fields, so the output looks like...
shape-square
shape-square
Controller
<?php
public function updateProducts($id, Request $request)
{
$featured = Input::has('featured') ? true : false;
$product = Product::findOrFail($id);
$product->update(array(
'product_name' => $request->input('product_name'),
'product_qty' => $request->input('product_qty'),
'product_sku' => $request->input('product_sku'),
'price' => $request->input('price'),
'reduced_price' => $request->input('reduced_price'),
'cat_id' => $request->input('cat_id'),
'brand_id' => $request->input('brand_id'),
'featured' => $featured,
'description' => $request->input('description'),
'product_spec' => $request->input('product_spec'),
));
$product->update($request->all());
$variants = VariantsOption::where('products_id', $id)->get();
$test = $request->all();
foreach ($variants as $v) {
$x = $v->id;
foreach ($test['variants_id'] as $key => $attrib) {
$var_name = $test['txt'][$key];
$varid = $attrib;
$variants = new VariantsOption;
$data = array(
'variants_id' => $varid,
'variants_name' => $var_name
);
$variants->where('id', '=', $x)->update($data);
}
}
return redirect('/admin/products/');
}
use following in your class
use Illuminate\Database\Eloquent\ModelNotFoundException;
OR add exception handler within your function
// Will return a ModelNotFoundException if no user with that id
try
{
$product = Product::findOrFail($id);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
dd(get_class_methods($e)) // lists all available methods for exception object
dd($e)
}
It looks like product with that $id is not found so on update it is adding new product in database.
I'm trying to create an Api using cakephp.
I generate a json on server and it works fine , but I tired to use pagination and I got a problem.
in the first case I take the image's path and I encode it to base64 and I generate json => works
in the second case I defined the pagination by the limits and the max and I kept the same code but as a result the image field is still the path from the database and it's not encoded
this my code in my controller :
class PilotsController extends AppController {
public $paginate = [
'page' => 1,
'limit' => 5,
'maxLimit' => 5
];
public function initialize() {
parent::initialize();
$this->loadComponent('Paginator');
$this->Auth->allow(['add','edit','delete','view','count']);
}
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $this->paginate($pilot));
$this->set('_serialize', ['pilot']);
}
}
If I remove the pagination from the code it works fine . Any idea how to fix it ??
I'd suggest to use a result formatter instead, ie Query::formatResults().
So you'll have something like this :
public function view($id) {
$pilot = $this->Pilots->find()
->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']]);
->formatResults(function($results) {
return $results->map(function($row) {
$image1 = file_get_contents(WWW_ROOT.$row['image_pilot']);
$row['image_pilot'] = base64_encode($image1);
return $row;
});
});
}
You can simply first paginate the data and then get the array values and after that modify that data as you want. Check this
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
$pilot = $this->paginate($pilot);
$pilot = $pilot->toArray();
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $pilot);
$this->set('_serialize', ['pilot']);
}
I am very much new to laravel framework.
I have one form , which i need to update on submit button click.
when submit button clicks control goes to controller.php 's update() function .
But I am unable to edit any field's value.
here is my code.
public function update($id)
{
//echo "<pre>";print_r(Input::all());exit;
$product = $this->product->find($id);
$input = Input::only('designer', 'sku', 'name', 'display_name', 'description', 'price', 'main_category', 'sub_category', 'lead_time', 'sizing', 'woven', 'body_fabric', 'lining_fabric', 'fit', 'primary_color', 'secondary_color', 'care_label', 'neck_type', 'closure', 'trims', 'special_finishings', 'image1', 'image2', 'image3', 'image4', 'image5','top', 'combo_products', 'keywords', 'visibility', 'featured');
//echo "<pre>";print_r($input);exit;
try
{
$this->adminNewProductForm->validate($input);
} catch(\Laracasts\Validation\FormValidationException $e)
{
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
$slug = Str::slug(Input::get('name'));
$slug = $this->product->getSlug($slug);
$input = array_add($input, 'slug', $slug);
DB::transaction(function() use($product, $input)
{
$product->fill($input)->save();
$stock_count = 0;
if(!empty(Input::get('xsmall_size')))
{
$rows = DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->get();
$stock_count += Input::get('xsmall_stock');
if(!empty($rows))
{
DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->update(array('variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
} else {
DB::table('products_variants')->insert(array('product_id' => $product->id, 'variant_name' => 'XS', 'variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
}
}
$input = array();
$input['flagship_status'] = Input::get('flagship_status');
if(Input::get('flagship_status'))
{
$input['stock_count'] = Input::get('small_stock');
}else {
$input['stock_count'] = $stock_count;
}
$product->fill($input)->save();
});
//echo "<pre>";print_r(Input::all());exit;
return Redirect::back()->withFlashMessage('Product Updated Successfully!');
}
Also I cant understand , what is going on by this line ? because i did not find validate function anywhere in my code.
$this->adminNewProductForm->validate($input);
I need to update table products not products_variants.
validate is inherited from the FormRequst class.
https://laravel.com/api/5.0/Illuminate/Foundation/Http/FormRequest.html#method_validate
You've provided too much code and too little information. You said you need to update a specific table, but yet there are two lines where you are very intentionally manually updating a database entry.
This is one of them:
DB::table('products_variants')->where('product_id', $product->id)->where('variant_name', 'XS')->update(array('variant_specs' => Input::get('xsmall_size'), 'price_change' => Input::get('xsmall_price'), 'total_stock' => Input::get('xsmall_stock'), 'stock_used' => 0));
When you call this:
$product->fill($input)->save();
It also saves 'dirty' (modified) models that also belong to it, which can include products_variants relationships. From the sound of it, you are incorrectly applying changes directly through SQL, and then the model's save method is overwriting it.
You seem unclear about what your code is actually doing, and I would strongly suggest simplifying it down and adding in code as you begin to understand what each line does. I think your question is the byproduct of copying an example and adding your own work without understanding how Laravel handles relationships and models. There is almost never a good reason to use raw SQL or DB statements.
Is there a better way of organizing or writing the below controller method in Laravel 5.1?
I want to keep my Controllers short and sweet. I am using a repository setup as i'm building quite a large application and I want to keep everything organised.
Please advise on the best way to organise the below code.
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create(CreateTimesheetRequest $request)
{
$data = $request->only('user_id', 'template_id');
$data['submitted_by'] = Auth::user()->id;
$timesheetId = $this->timesheet->createTimesheet($data);
foreach($request->get('row') as $key => $row)
{
foreach($row as $field => $value)
{
$this->timesheet->saveTimesheetRows([
'timesheet_id' => $timesheetId,
'field_id' => $this->timesheetFields->where('name', $field)->first()->id,
'field_name' => $field,
'field_value' => $value,
'field_key' => $key
]);
}
}
return Redirect::back()->withMessage('The timesheet was successfully created.');
}
All I can suggest - move this:
$data = $request->only('user_id', 'template_id');
$data['submitted_by'] = Auth::user()->id;
... into yours request class. For example, into some data() method:
class CreateTimesheetRequest ... {
...
public function data() {
return array_merge(
$this->only('user_id', 'template_id'),
['submitted_by' => Auth::user()->id]
);
}
}
Also, $this->timesheet->saveTimesheetRows(array) looks more like $this->timesheet->saveTimesheetRow(array) for me - name intends to save multiple rows, but you feed that method only with one row per call.
Maybe, you can refactor that method to smth. like this:
function saveTimesheetRows($timesheetId, $key, $rows, $fieldIds) {
foreach($rows as $field => $value) {
$this->saveTimesheetRow([
'timesheet_id' => $timesheetId,
'field_id' => $fieldIds[$field],
'field_name' => $field,
'field_value' => $value,
'field_key' => $key
]);
}
}
function saveTimesheetRow(array $row) {
// old saveTimesheetRows implementation
}
Upd.
And another tip: use Eloquent's keyBy() method like so:
$keyIDs = $this->timesheetFields->whereIn('name', $fields)->get(["name", "id"])->keyBy("name");
So, finally:
public function create(CreateTimesheetRequest $request) {
$data = $request->data();
$timesheetId = $this->timesheet->createTimesheet($data);
foreach($request->get('row') as $key => $row) {
$this->timesheet->saveTimesheetRows(
$timesheetId,
$key,
$row,
$this->timesheetFields
->whereIn('name', array_keys($row))
->get(["name", "id"])
->keyBy("name") // probably, can be moved into $this->timesheetFields implementation
);
}
return Redirect::back()->withMessage('The timesheet was successfully created.');
}