How to add an array within a foreach in laravel controller? - laravel

I am trying to insert data from a form which i get it in the form of an array and i am using a foreach to insert the data each in to the database. amongst these data i have another array that i need to insert it in the form of an array.
The Amendities should be saved in the form of an array! i tried using implode but didn't quite get the results i expected.
foreach ($request->room_type as $item => $v) {
$data2 = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => implode($request->amendities),
'hotel_id' => $hotel->id,
);
dd($data2);
Rooms::insert($data2);
}
impoding Amendities array saves the data as a string but i am trying to get the values as an array.

u need to prepare a datasets to insert multiple record
so u can try like this
$data2 = [];
foreach ($request->room_type as $item => $v) {
$opt = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => json_encode($request->amendities),
'hotel_id' => $hotel->id,
);
array_push($data2,$opt);
}
Rooms::insert($data2);

Thank you for the help guys this is final solution which worked for as per your help
foreach ($request->room_type as $item => $v) {
$opt = array(
'room_type' => $request->room_type[$item],
'no_of_pax' => $request->no_of_pax[$item],
'no_of_pax_children' => $request->no_of_pax_children[$item],
'cost_per_adult' => $request->cost_per_adult[$item],
'cost_per_child' => $request->cost_per_child[$item],
'room_description' => $request->room_description[$item],
'amendities' => json_encode($request->amendities),
'hotel_id' => $hotel->id,
);
array_push($data2, $opt);
}
Rooms::insert($data2);
Thank you for your help all of you!

Related

Undefinde offset:1 when importing laravel excel

this my code cause the trouble,
$cust = Customer::where('name', '=', $data[$i][0]['customer_name'])
->pluck('customer_id')[0];
this one for get customer id when i do store to sales order
$sales = array(
'customer_id' => Customer::where('name', '=', $data[$i][0]['customer_name'])->pluck('customer_id')[0],
'logistics_id' => Logistic::where('logistics_name', '=', $data[$i][0]['logistics'])->pluck('logistics_id')[0],
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp']
);
$store_so = SalesOrder::create($sales);
but, when i do dd(), i get the right data
First of all, you need to check if the $data variable returns the data as you expect.
dd($data);
Next, you need to check that the $data array has the number of elements according to $total_data.
dd(count($data) == $total_data));
So basically, you just need to give condition or try-catch (recommended) :
if (isset($data[$i][0])) {
$customer = Customer::where('name', $data[$i][0]['customer_name'])->first();
$logistic = Logistic::where('logistics_name', $data[$i][0]['logistics'])->first();
if(!$customer){
dd('No customer found!');
}
if(!$logistic){
dd('No logistic found!');
}
$sales = [
'customer_id' => $customer->customer_id,
'logistics_id' => $logistic->logistics_id,
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp'],
];
$store_so = SalesOrder::create($sales);
}
else{
dd('No $data[$i][0] found!');
}
PS : I recommend using the first() method instead of pluck('customer_id')[0].
It seems you need to get a customer_id from a customer_name.
Try to make everything simple:
$sales = array(
'customer_id' => Customer::where('name', $data[$i][0]['customer_name'])->first()->id,
...
);

create associative array with key and value generated in for

i´m traying to create associative array, from query in laravel.
public function assignAllCall(Request $request)
{
$callList = [];
$newCall = [];
for($i=0; $i<count($request->get('calls')); $i++){
array_push($callList, Listado::where('id', $request->get('calls')[$i])->get());
}
for($i=0; $i<count($callList); $i++){
for($j=$i; $j<count($callList[$i]); $j++){
$newCall = [
'nomape' => $callList[$i][$j]->nomape,
'direccion' => $callList[$i][$j]->direccion,
'provincia' => $callList[$i][$j]->provincia,
'ciudad' => $callList[$i][$j]->ciudad,
'cp' => $callList[$i][$j]->cp,
'telefono' => $callList[$i][$j]->telefono,
'movil' => $callList[$i][$j]->movil,
'id_teleoperadora' => $request->get('teleoperadora'),
'id_estado' => 1,
'fecha_asignacion' => Carbon::now()->format('Y-m-d H:m:s'),
'created_at' => Carbon::now()->format('Y-m-d H:m:s'),
];
}
print_r($newCall);
// create call
//$result = Llamada::create($newCall);
}
//return $result;
}
i have this function that receive param from ajax and this values it´s ids array.
I need get all data from this ids for get all data and create new calls with this data, for this i have one for to do query and assign to array. after i´m traying to create associative array but when i do print_r always i return same result:
Array
(
[nomape] => x
[direccion] => x
[provincia] => x
[ciudad] => x
[cp] => x
[telefono] => x
[movil] => x
[id_teleoperadora] => x
[id_estado] => x
[fecha_asignacion] => x
[created_at] => x
)
always same value. I don´t know if i do well my function or have one better solution for to do this.
Thanks for read and thanks for help.
Instead of
for($j=$i; $j<count($callList[$i]); $j++){
try this:
for($j=0; $j<count($callList[$i]); $j++){

Codeigniter update_batch--view, but not execute

I am using Codeigniter 3.x and want to see an update_batch query, but not run it, while I am debugging the code.
This works for an update_batch:
$this->db->update_batch("`" . $this->fullGamesTable . "`", $fullGames, 'gameid');
and updates the database, but I want to view the update and not actually do the update.
Thanks.
Can you do like this
$data = array(
array(
'opt_id' => $hoptid1,
'q_id' => $hid,
'opt_val' => $sin_yes,
'opt_crct' => $sin_yescrt,
'opt_mark' => '1'
),
array(
'opt_id' => $hoptid2,
'q_id' => $hid,
'opt_val' => $sin_no,
'opt_crct' => $sin_nocrt,
'opt_mark' => '1'
)
);
$this->db->update_batch('option', $data, 'opt_id');
Try this
public function update_batch()
{
$data = $this->db->select('id,description')->from('insert_batch')->group_by('url')->get()->result_array();
$batch_update = [];
foreach ($data as $key => $value) {
$value['description'] = 'description';
$batch_update[] = [
'id' =>$value['id'],
'description' => $value['description']
];
}
echo "<pre>"; print_r($batch_update);
$this->db->update_batch('insert_batch',$batch_update,'id');
}

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

Filtering invoice collection by created_at in magento

I'm trying to find a way to filter the results of getInvoiceCollection in the function below:
// "eachInvoice" is each of the Invoice object of the order "$orders"
if ($order->hasInvoices()) {
foreach ($order->getInvoiceCollection() as $eachInvoice) {
$invoiceIncrementId = $eachInvoice->getIncrementId();
}
}
Can adding the filter below to $order->getInvoiceCollection()
$order->getInvoiceCollection()
->addAttributeToFilter('created_at', array(
'from' => $from_date,
'to' => $today,
'date' => true,));
So the entire function would be, is the correct way to do this, it doesn't seem like its right.
// "eachInvoice" is each of the Invoice object of the order "$orders"
if ($order->hasInvoices()) {
foreach ($order->getInvoiceCollection()$order->getInvoiceCollection()
->addAttributeToFilter('created_at', array( 'from' => $from_date,
'to' => $today, 'date' => true,)) as $eachInvoice) {
$invoiceIncrementId = $eachInvoice->getIncrementId();
}
}
Whats the "correct way" to go about doing this?
To get the increment ids as is shown in your sample code there is no need to loop:
$invoiceCollection = $order->getInvoiceCollection();
$invoiceCollection
->addAttributeToFilter('created_at', array(
'from' => $from,
'to' => $to,
));
$incrementIds = $invoiceCollection->getColumnValues('increment_id');

Resources