Passing multiple values using - laravel

I want to pass multiple values in single column of database.
I have two tables (Schedule & Days). In form I select days when I select multiple days then I should add in db multiple. But it add only one day
public function store(Request $request)
{
$schedule = new menu;
$days = new day;
$sensor = new sensor;
$schedule->scheduleName = $request->name;
$schedule->start_time = $request->start_time;
$schedule->end_time = $request->end_time;
$schedule->timestamps = false;
$schedule->s_daytime = $request->s_daytime;
$schedule->e_daytime = $request->e_daytime;
$days->days = $request->days;
$days->timestamps = false;
$sensor->timestamps = false;
$sensor->sensor = $request->sensor;
$schedule->save();
$days->schedule_id = $schedule->id;
$days->save();
$sensor->schedule_id = $schedule->id;
$sensor->save();
return view('store');
}

What you can do is you can pass multiple days in an array and store the array in json format on your DB. here is the snippets.
$days_list = $request->days_list;
//for edit previous data
if(!empty($days->days_list)){
$arr = json_decode($days->days_list);
if(in_array($request->days, $arr)){
$data['success'] = false;
$data['message'] = 'This Day is already on your schedule
list.';
return $data;
}
array_push($arr, $days_list);
$days->days_list = json_encode($arr);
}
// for adding new data
else{
$days->days_list = json_encode(array($request->days_list));
}
$days->save();
```

Related

Display large array in laravel blade in too much time

so i got imported my large excel file with huge informations with 1 sec and i did get all the information i need to display within 1 sec to , but i got a big probleme when displaying the array in the view coz i m testing if the cells are correct or not i m using 5 ifs and 3 foreach and it takes mote than 2 mins , i need help to display all the info in a short time this is my array , and thanks
and there is my code of the view which takes to much time to display infos
and thanks
//here we get our final result of true and false fields
$finale_array = [];
// here we get all our
$current_table2 = [];
$results_applied = [];
$current_result = [];
$columns = SCHEMA::getColumnListing('imports');
// here we get all our conditions
$conditions = DB::table('conditions')->select('number', 'field', 'value')->get();
// here we get all our data
$imports = DB::table('imports')->get();
$results = DB::table('results')->get();
$x = 0;
$default_value = 0;
foreach ($imports as $key => $imported) {
$res = get_object_vars($imported);
foreach ($conditions as $value) {
$array = get_object_vars($value);
$result = $this->test($columns, $array['field']); // the result of our test function
if ($result == "ok") {
if ($res[$array['field']] == $array['value']) {
foreach ($results as $value_result) {
$res_resultat = get_object_vars($value_result);
$test_field = $this->test($columns, $res_resultat['field']);
// testing if the condtion numder match with the result number
if (($res_resultat['condition_number'] == $array['number'])) {
if (($test_field == 'ok')) {
if ($res['id'] != $default_value) {
// here test if the difference between the id and the default value is different from the current id to insert
if (($res['id'] - $default_value) != $res['id']) {
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
$current_table2 = [];
$results_applied = [];
$default_value = $res['id'];
}
$current_table2 = [$res, $res['id']];
}
$current_result = [$res_resultat['field'], $res[$res_resultat['field']]];
if ($res_resultat['value'] == $res[$res_resultat['field']]) {
$current_result[2] = 'true';
$current_result[3] = $res_resultat['value'];
} else {
$current_result[2] = 'false';
$current_result[3] = $res_resultat['value'];
}
$current_result[4] = $array['number'];
array_push($results_applied, $current_result);
}
}
}
}
}
}
$default_value = $res['id'];
}
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
dd($finale_array);
return view('Appliedconditions', ['imports' => $finale_array, 'columns' => $columns]);
}
From what I can see, you are recovering all the data without paging it.
You must paginate the data using the paginate(#elements_per_page) directive in your query, where #elements_per_page is the number of elements you want to display per page.
For example:
$elements = Elements::select('*')->paginate(10);
and in your blade view you can retreive pagination links after the closing table tag in this way: {{ $elements->links() }}

model and controller query to merge timein and timeout with single row in codeigniter

Please teach me how can I achieve this(Codeigniter framework)
Please see images that I want to achieve thank you.
and I'm also new to codeigniter and want to understand the answer.
enter image description here
Here is my database:
enter image description here
model
public function get_attendance_employees() {
$sql = 'SELECT * FROM tbl_employee';
//$binds = array(1);
$query = $this->db->query($sql);
return $query;
}
public function attendance_first_in_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein' limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql,$binds);
return $query;
}
public function attendance_first_in($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein'";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
public function attendance_first_out_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query;
}
public function attendance_first_out($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
controller
public function attendance_bio()
{
$session = $this->session->userdata('username');
if(!empty($session)){
$this->load->view("admin/timesheet/attendance_bio", $data);
} else {
redirect('admin/');
}
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$attendance_date2 = $this->input->get("attendance_date"); //string
//$ref_location_id = $this->input->get("location_id");
//$convert_atten = strtotime($attendance_date2); //int value
//$attendance_date = $convert_atten->format('m-d-Y');
$attendance_date = date("m-d-Y",strtotime($attendance_date2));
//$timein = $this->Bio_model->get_attendance_date();
//$timein = $this->Bio_model->get_attendance_timein($get_day);
//$timein = $this->Bio_model->get_all();
$employee = $this->Bio_model->get_attendance_employees();
$data = array();
//var_dump($attendance_date);
foreach($employee->result() as $r){
$check = $this->Bio_model->attendance_first_in_check($r->userid,$attendance_date);
if($check->num_rows() > 0){
// check clock in time
$first_in = $this->Bio_model->attendance_first_in($r->userid,$attendance_date);
//$first_in2 = $first_in[0]->time->format('m-d-Y');
// clock in
$clock_in = new DateTime(strtotime($first_in[0]->time));
//$clock_in2 = $clock_in->format('H:i');
$clock_in2 = date_format($clock_in->time, 'H:i');
//$clock_in2 = var_dump($clock_in);
} else {
$clock_in2 = '-';
$clock_in = '-';
}
$check_out = $this->Bio_model->attendance_first_out_check($r->userid,$attendance_date);
if($check_out->num_rows() == 1){
$first_out = $this->Bio_model->attendance_first_out($r->userid,$attendance_date);
//$first_out2 = $firs
$clock_out = new DateTime(strtotime($first_out[0]->time));
if ($first_out[0]->time!='') {
//$clock_out2 = $clock_out->format('H:i');
//$clock_out2 = date('H:i',$clock_out);
$clock_out2 = date_format($clock_out->time, 'H:i');
} else {
$clock_out2 = '-';
}
}else {
$clock_out2 = '-';
$clock_out = '-';
}
$data[] = array(
$r->userid,
$attendance_date,
$clock_in2,
$clock_out2,
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $employee->num_rows(),
"recordsFiltered" => $employee->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
Thank you for providing more information on the topic and the code you have attempted so far. I have supplied an algorithm which I believe will work for you.
Contoller:
<?php namespace App\Controllers;
use App\Models\EmployeeTimeLog;
class Home extends BaseController
{
public function index($employeeId)
{
// get all between dates
$emplyeeModel = new EmployeeTimeLog();
// get one week before today - for example
$startDate = date("Y-m-d", strtotime("-1 week"));
$endDate = date("Y-m-d");
// get clock-in and clock-out for employee between dates
$timeIn = $emplyeeModel->getTimeIn($employeeId, $startDate, $endDate)->getResult();
$timeOut = $emplyeeModel->getTimeOut($employeeId, $startDate, $endDate)->getResult();
$timeInIndex = 0;
$timeOutIndex = 0;
$output = [];
$nextDate = $startDate;
// loop through all the days between start and end date
while($nextDate < $endDate){
// get the lowest "timein" datetime which is the same date as the search date $nextDate
$nextTimeIn = NULL;
while($timeInIndex < count($timeIn) && date("Y-m-d", strtotime($timeIn[$timeInIndex]->Time)) == $nextDate){
if(is_null($nextTimeIn)){
$nextTimeIn = $timeIn[$timeInIndex];
}
$timeInIndex ++;
}
// get the highest "timeout" datetime which is the same day as the search date $nextDate
$nextTimeOut = NULL;
while($timeOutIndex < count($timeOut) && date("Y-m-d", strtotime($timeOut[$timeOutIndex]->Time)) == $nextDate){
$nextTimeOut = $timeOut[$timeOutIndex];
$timeOutIndex ++;
}
// enter into a 2 dimentional array with
// index 0 = timein
// index 1 = timeout
$output[] = [$nextTimeIn, $nextTimeOut];
// get the next date
$nextDate = date('Y-m-d', strtotime($nextDate. ' + 1 days'));
}
// return view with data
return view('welcome_message', ["output" => $output]);
}
}
Model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeTimeLog extends Model{
private $tableName = "tbl_employee_time_log";
public function __construct(){
$db = \Config\Database::connect();
$this->builder = $db->table($this->tableName);
}
private function timeData($employeeId, $startDate, $endDate){
// builder function DRY
$this->builder->where("EmployeeId", $employeeId);
$this->builder->where("Time >", $startDate);
$this->builder->where("Time <", $endDate);
$this->builder->orderBy("Time", "ASC");
}
public function getTimeIn($employeeId, $startDate, $endDate){
// call builder function and add timeIn to only get clock in times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timein");
return $this->builder->get();
}
public function getTimeOut($employeeId, $startDate, $endDate){
// call builder function and add timeout to only get clock out times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timeout");
return $this->builder->get();
}
}
?>
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Timesheets</title>
</head>
<body>
<h1>Timesheets</h1>
<?php
echo "<h1>Times</h1>";
foreach ($output as $times) {
echo "Time in: ";
if(!is_null($times[0])){
echo $times[0]->Time;
}else{
echo "-";
}
echo " Time out: ";
if(!is_null($times[1])){
echo $times[1]->Time;
}else{
echo "-";
}
echo "<br>";
}
?>
</body>
</html>
Output:
Database:
The whole algorithm works by searching through the date between the start and end date of the dates provided. You can then check any timein and timeout values which have the same date as the loop date. If a date cannot be found, the default is NULL which is replaced by "-" in the view.
The algorithm specifically gets the earliest timein and the latest timeout value for the employee. This means that if the employee clocks-in twice in one day the earliest date will be used and the opposite for clock-out.
This algorithm specifically works for one employee, but just use your select * employees and loop through instead of the employeeId on the controller. You may want to look in the documentation for the Query Builder in CodeIgniter it makes querying the database much easier, and will escape data to protect from SQL Injections etc.
It could be better to redesign your database table and check on insert rather than manipulate on select. Where you have one row for each day and the timein and timeout which represent the time. Something like this:
You can check to see if the date already exists, if so override the current value if needed. If the current date doesn't exist for that employee create a new record.
If you need any clarification, let me know,
Thanks,

Save multidimensional array using Laravel and ajax

I am building a pharmacy management system. I have a condition where I need to build a section
As shown in the picture, I need to store the data where the upper three should be same for all of the rows inputted below.
The form data is submitted as in the below picture.
But the data when looped and saved is not being saved as desired. Only the last row of the data is being inserted and I am also confused to store supplier, purchase date and note since these data should be repeated as many as the number of rows are added.
PurchaseController.php
public function storePurchase(PurchaseStoreRequest $request)
{
$purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}
Can someone help me to store these three fields in the database repeating the number of rows submitted ?
Currently only the last row is being inserted into the database.
This might be an another way to accomplish what you're looking for.
$sharedKeys = ['supplier', 'purchase_date', 'description'];
$sharedData = $request->only($sharedKeys);
$multiKeys = ['category', 'name', 'generic_name', 'batch_number', 'company', 'strength', 'expiry_date', 'quantity', 'selling_price', 'purchase_price'];
$multiData = $request->only($multiKeys);
for ($i = 0; $i < count($request->name); $i++) {
$individualData = array_combine($multiKeys, array_column($multiData, $i));
Purchase::create($sharedData + $individualData);
}
For every loop, you need to create a new instance, then It will create a new record on each loop :
public function storePurchase(PurchaseStoreRequest $request)
{
// $purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase = new Purchase(); // create new instance end with (); on each loop
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}

Laravel 5.3 database transaction issue?

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

Create category programmatically in multiple languages in Magento

i am tyring to add categories programmatically for german and english languages.
website-ID: 1
website store-ID: 1
view-ID english, code "en" => 1
view-ID german, code "de" => 2
$category['general']['path'] = $v['cat_name_de'];
$category['general']['name'] = $v['cat_name_de'];
$category['general']['meta_title'] = "";
$category['general']['meta_description'] = "";
$category['general']['is_active'] = 1;
$category['general']['url_key'] = urlencode($v['cat_name_de']);
$category['general']['display_mode'] = "PRODUCTS";
$category['general']['is_anchor'] = 0;
$category['category']['parent'] = $v['magento_cat_id'];
$storeId = 0; // default
$magento_subcat_id = createCategory($category, $storeId);
...
function createCategory($data, $storeId) {
echo "Erzeuge '{$data['general']['name']}' - Elternkategorie:
[{$data['category']['parent']}] ...";
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
}
if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) &&
!$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
}
try {
$category->save();
return $category->getId();
} catch (Exception $e) {
return FALSE;
}
}
}
What i am puzzling with at the moment is setting view-ID individually for passing the $category['general']['name'] for each language.
I tried to set each language string with a foreach setting english/german texts. But this did not work out, because i somehow mixed up setting the view correctly.
To make it short:
Creating categories and subcategories like this does work very good, but i do not get it to work to pass english/german categoty titles.
Thanks guys
For all of you who are struggeling with this situation i made a workaound like this:
I added all those values to the affected database tables directly. This is for sure a quick and dirty way, but it does the job.
For all in need of some ideas here is the (undocumented) snipped belonging to my initial post.
// Get values for next language insert
$entity_type_id = $category
->getResource()
->getTypeId();
$entity_id = $category->getEntityId();
$read_entity = Mage::getSingleton('core/resource')
->getConnection('core_write');
$sql_entity = "SELECT * FROM eav_attribute WHERE
`attribute_code` = 'name' AND
`entity_type_id` = " . $entity_type_id . ";";
$row_entity = $read_entity
->fetchRow($sql_entity);
$attribute_id = $row_entity['attribute_id'];
// prepare value for name field in different langauge
$val = Mage::getSingleton('core/resource')
->getConnection('default_write')
->quote($v['en']);
$sql_insert = "INSERT INTO `catalog_category_entity_varchar`
(`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`)
VALUES ($entity_type_id,$attribute_id,$storeId,$entity_id,$val);";
$read_entity->query($sql_insert);
I hope this helps someone out who is in need of this.

Resources