Cant change single value in session array in Laravel - arrays

This my method update for products. And cant to change qty of product. Data saved inside foreach, but nothing change out of this. I can't understand what the problem.
if (!session()->has('products')) {
session()->put('products', []);
}
$products = session()->get('products');
foreach ($products as $item) {
if (isset($item[$product->id])) {
$item[$product->id]['qty'] = 10;
dd($products); // dd($item) - changes
$request->session()->put('products', $products);
return redirect()->back();
}
}
session()->push('products', [
$product->id => [
'product' => $product,
'qty' => 1
]
]);
return redirect()->back();
As you can see there is dd($products) - so its not change. But if dd($item) so it has qty 10.

I can solved this with next:
foreach ($products as $key => $value) {
if (isset($value[$product->id])) {
$value[$product->id]['qty'] = 10;
$products[$key] = $value;
$request->session()->put('products', $products);
return redirect()->back();
}
}
Just add a $key => $value and save it in $products[$key] = $value;

Related

Laravel - How to insert multi-dimensional Array in DB

I have the array as below;
I'd like to insert each name keys into tableName and get the inserted id.
For the steps, each of them will be inserted into another table tableSteps including the last inserted id of the name.
Like as below screenshot.
In my controller,
Here's what I've done so far.
$instructionsArrays = $request->instructions;
$max = count($instructionsArrays);
for ($x = 1; $x <= $max; $x++) {
foreach($instructionsArrays as $instructionsArray){
Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $x],
['name' => $instructionsArray['name']],
);
}
}
I was able to save sequence numbers but for names it saves only the last name key.
And... I'm really lost..
You can achieve what you want from 2 for loops
foreach($request->instructions as $key => $val){
$id = Instruction::insertGetId(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
['name' => $val['name']],
);
$data = []; //bulk insertion
$created_at = now();
foreach($val["steps"] as $step){
array_push($data, ["header_id" => $id, "name" => $step, "sequence" => $key+1, "created_at" => $created_at]); //why insert sequence when you can obtain it from the relationship?
}
Steps::insert($data);
}
With the help of the answer of #Kneegrows, I came up with the code below and it is now working. Thank you.
foreach ($request->instructions as $key => $val) {
$instruction = Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
['instructions_name' => $val['name']],
);
$id = $instruction->id;
$data = []; //bulk insertion
$i = 1;
foreach ($val["steps"] as $step) {
if(!is_null($step)){
array_push($data, ["instruction_id" => $id, "steps_name" => $step, "sequence" => $i]);
$i++;
}
}
Steps::insert($data);
}

can not use pagination() for an array object in laravel

I am constructing an array in Laravel 5.7. I would like to paginate it, but it errors because of array feature. what shall I do?
In MyController.php:
$result = array();
foreach ($sameDateMatches as $key => $date) {
array_push($result, [
'date' => $key,
'day_of_week' => getDayOfWeek($key),
'matches' => $date,
]);
}
if (!empty($_GET['page'])) {
$result = $result->paginate(10);
$pagination = $result;
} else {
$result = $result;
$pagination = null;
}
return returnSuccessfulResponse(
trans('api.response.successful.show'),
[
'Scheduled Matches' => $result,
],
$pagination
);
Call to a member function paginate() on array
You can only use paginate on an instance of QueryBuilder or on an Eloquent query.
Instead, if you need to 'paginate' an array, you can use PHP array_chunk.
array_chunk($result, 10, true);
I solved my problems using make() and LengthAwarePaginator as below:
if (!empty($_GET['page'])) {
$per_page = !empty($_GET['per_page']) ? $_GET['per_page'] : 10;
$page = $_GET['page'];
$result = $result instanceof Collection ? $result : Collection::make($result);
$result = new LengthAwarePaginator(
$result->forPage($page, $per_page)->values(),
$result->count(),
$per_page,
$page,
['path' => request()->url()]
);
$pagination = $result;
} else {
$pagination = null;
}

how to show as row_number() in codeignitier

need help what wrong with my code where this my sql command where successfull run in mysql :
SELECT func_inc_var_session() As row_number ,
vruasjalan2.*
FROM vruasjalan2 Where skid = #skid
ORDER BY kategoriruasjalanid, subkategoriruasjalanid,ruasjalanid;"
but when i want to display in my controller row_number start error say"Call to undefined method Jalan_model::num_rows()"
public function ajax_list()
{
$list = $this->Jalan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $Jalan) {
$no++;
$row = array();
$row[] = $no;
$row[] = $Jalan->row_number;
$row[] = $Jalan->ruasjalanid;
$row[] = $Jalan->skid;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Jalan->count_all(),
"recordsFiltered" => $this->Jalan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
}
and this is my model
public function get_list_companys()
{
$this->db->select('vruasjalan2.*');
$this->db->from($this->table);
$this->db->order_by('kategoriruasjalanid','asc');
$query = $this->db->get();
$result = $query->result();
$companys = array();
foreach ($result as $row)
{
$companys[] = $row->kategoriruasjalanid;
}
return $companys;
}
if there any expert know this problems

Writing custom rules for CakePHP model

use App\Model\Rule\CustomIsUnique;
$rules->add(new CustomIsUnique(['item_id', 'manufacture_unit_id']), [
'errorField' => 'item_id',
'message' => 'Item Unit must be unique.'
]);
On CustomIsUnique I've copy pasted codes of IsUnique
Cake\ORM\Rule\IsUnique;
But How to extend or add more operations inside the __invoke method ?
Update ::
public function __invoke(EntityInterface $entity, array $options)
{
$result = parent::__invoke($entity, $options);
if ($result) {
return true;
} else {
if ($options['type'] == 'item_units') {
$data = TableRegistry::get('item_units')->find()
->where(['item_id' => $entity['item_id'],
'manufacture_unit_id' => $entity['manufacture_unit_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
} elseif ($options['type'] == 'production_rules') {
$data = TableRegistry::get('production_rules')->find()
->where(['input_item_id' => $entity['input_item_id'],
'output_item_id' => $entity['output_item_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
} elseif ($options['type'] == 'prices') {
$data = TableRegistry::get('prices')->find()
->where(['item_id' => $entity['item_id'],
'manufacture_unit_id' => $entity['manufacture_unit_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
}
}
}
this is how I've implemented for different model and passed extra parameter along with options array. I think this is not the good way to do this.
If you want to extend a core application rule, you can do something like:
<?php
use App\Model\Rule;
class CustomIsUnique extends Cake\ORM\Rule\IsUnique
{
public function __invoke(EntityInterface $entity, array $options)
{
$result = parent::__invoke($entity, $options);
if ($result) {
// the record is indeed unique
return true;
}
// do any other checking here
// for instance, checking if the existing record
// has a different deletion status than the one
// you are inserting
}
}
That will let you add any additional logic for your application.

CodeIgniter Session do not saving Array

i using CodeIgniter Session with database for save a array with $_FILES, but don't save. I do this (but the array never increment):
The post of form, redirects to himself.
Function to upload e load the page of upload.
public function getUpload($codtemp, $codmessage){
$this->load->library('session');
$this->layout = '';
$data = array();
$data['codmessage'] = $codmessage;
$data['codtemp'] = $codtemp;$tempfiles= $this->session->userdata('tempfiles');
if (isset($_FILES['attachment']))
{
$files = $this->fixGlobalFilesArray($_FILES['attachment']);
foreach($files as $file)
{
$tempfiles[$codtemp][] = $file;
}
$this->session->set_userdata('tempfiles', $tempfiles);
unset($files);
}
$this->parser->parse('attachment_upload', $data);
}
private static function fixGlobalFilesArray($files) {
$ret = array();
if(isset($files['tmp_name']))
{
if (is_array($files['tmp_name']))
{
foreach($files['name'] as $idx => $name)
{
$ret[$idx] = array(
'name' => $name,
'tmp_name' => $files['tmp_name'][$idx],
'size' => $files['size'][$idx],
'type' => $files['type'][$idx],
'error' => $files['error'][$idx]
);
}
}
else
{
$ret = $files;
}
}
else
{
foreach ($files as $key => $value)
{
$ret[$key] = self::fixGlobalFilesArray($value);
}
}
return $ret;
}
Before save the array, serialize the data and after get the data, unserialize. If data is empty, create a array

Resources