Laravel - Insert a model multiple times - php

I have a model that I change some attributes I want to insert it but Eloquent, after the first save() will automatically do an update while I'm using save() method, here is my code:
for ($i = 0; $i < $range; $i++) {
$model->attr = "Some new value";
$model->save(); // after the first save() will do update but I want to an insert
}

You need to create a new instance of the Model every time you loop through. Try this:
for ($i = 0; $i < $range; $i++) {
$model = new Product;
$model->attr = "Some new value";
$model->save(); // after the first save() will do update but I want to an insert
}
I am not sure what your Model name is but I used Product in this instance. Replace this with your Model name.

You can use create
$attributes = [
'foo' => 'bar'
];
for ($i = 0; $i < $range; $i++) {
$attributes['foo'] = 'bar'.$i;
Model::create($attributes);
}
Or if you want create a function in your model:
public function saveAsNew(){
$this->exists = false;
$this->attributes[$this->primaryKey] = null; // reset the id
return $this->save();
}
Also I wrote this function, that saves the same model multiple times (yes I know that's not what your after but I wanted to post it anyways:
public function saveMultiple($times){
$saved = true;
for($i = 0; $i < $times; $i++){
if(!$this->save()){
$saved = false;
}
$this->attributes[$this->primaryKey] = null; // unset the id
$this->exists = false;
}
return $saved;
}

Related

Laravel Nova create same record multiple times

I am stuck with a issue on Laravel. I like to insert a records multiple times.
The user can add a amount, lets say 3. Than the insert query has to run 3 times.
I was able to make a observer but when i loop through there, it will still add one.
See the code below:
public function creating(CardOrder $cardOrder)
{
if($amount = $cardOrder->amount) {
unset($cardOrder->amount);
for($i = 0; $i < $amount; $i ++) {
$cardOrder->entity_id = 1234;
$cardOrder->group_id = 'test';
}
}
}
Is there a way to do that, and do i need a observer to accomplish that?
Thank you in advance.
Just added them $cardOrder = new CardOrder;
public function creating(CardOrder $cardOrder)
{
if($amount = $cardOrder->amount) {
unset($cardOrder->amount);
$cardOrder = new CardOrder;
for($i = 0; $i < $amount; $i ++) {
$cardOrder->entity_id = 1234;
$cardOrder->group_id = 'test';
$cardOrder->save();
}
}
}

adding new key value is not working

This is my json link which stored in variable named $onceBooking.
I want to count total booking days. If booking array is empty then add total_days = 0 but but if it is not empty then i am counting the unique booking_slots and adding them into main array. I am getting the correct count but when i am adding this into main it showing me this error.
$data = json_decode($onceBooking);
for ($i = 0; $i < count($data); $i++) {
if (count($data[$i]->bookings) == 0) {
$data[$i]->total_days = 0;
} else {
$bookings = $data[$i]->bookings;
for ($j = 0; $j < count($bookings); $j++) {
$booking_slots = $bookings[$j]->booking_slots;
$final_array = array();
$uniquekeys = array();
foreach ($booking_slots as $key => $data) {
if (!in_array($data->date, $uniquekeys)) {
$uniquekeys[] = $data->date;
$final_array[$key] = $data;
}
}
}
$data[$i]->total_days = count($final_array);
}
}
return $data;
Change your call to json_decode() to return an array by adding true as the 2nd argument.
// change this
$data = json_decode($onceBooking);
// to this
$data = json_decode($onceBooking, true);

Generating set of random unique codes in php

I'm trying to generate a set of unique Alpha Numeric code in php. I tried using anonymous function and closures.
Here when I generate more than 1000 codes, there are changes of codes getting duplicate. So I tried to generate a new code if any duplicate found.
Below is my code which isn't working as expected, I'm getting "still DUPLICATE Exist" a few times and its not regenerating code even a single time.
$start = 0;
$count = 10;
$codes = [];
$another = $this;
for ($i=$start; $i < $count; $i++) {
$getUniqueCode = function (&$codes) use ($another, &$getUniqueCode) {
$newCode = $another->genRandomCode();
if (in_array($newCode, $codes)) {
echo "Regenerate on DUPLICATE FOUND - $newCode <br/>";
return $getUniqueCode($codes);
} else {
return $newCode;
}
};
$newCode = $getUniqueCode($codes);
if (\in_array($newCode, $codes)) {
echo "still DUPLICATE Exist - $newCode <br/>";
}
array_push($codes, $newCode);
}
private function genRandomCode()
{
$str = "ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
$randInt = rand(1000000, 9999999);
$randString = "";
for ($i=0; $i < 6; $i++) {
$randRem = $randInt % 36;
$randInt = $randInt / 36;
$randString .= $str[$randRem];
}
return $randString;
}
Your original code recurses, but i don't think you need to do that.
$start = 0;
$count = 10;
$codes = [];
$another = $this;
for ($i=$start; $i < $count; $i++) {
//do not pass $codes as a reference here
$getUniqueCode = function ($codes) use ($another)
{
$newCode = $another->genRandomCode();
while(in_array($newCode, $codes))
{
echo "Regenerate on DUPLICATE FOUND - $newCode <br/>";
}
return $newCode;
};
$newCode = $getUniqueCode($codes);
if (\in_array($newCode, $codes)) {
echo "still DUPLICATE Exist - $newCode <br/>";
}
array_push($codes, $newCode);
}
Arguably however, a better way to handle a coupon system like this is to generate the possible coupon codes beforehand, store them in a database, and select one at random for activation. this guarantees a unique code, and lets you keep track of which codes you have used so far.

Recursive Functions and linked lists PHP

I was given a quiz by an employer to determine my ability as a programmer and the test was more or less "Write a function that counts the length of this linked list". I failed the quiz because for whatever reason my function didn't return anything (It was a timed quiz). This is my code.
class IntList{
var $value = 1;
var $next = null;
}
$A = new IntList();
$B = new IntList();
$C = new IntList();
$D = new IntList();
$A->next = $B;
$B->next = $C;
$C->next = $D;
main($A);
$count = 0;
function main($L)
{
global $count;
$final = getListLength($L, $count);
print $final;
}
function getListLength($L, $count)
{
if (isset($L->next))
{
$count++;
getListLength($L->next, $count);
} else
{
print $count;
return $count;
}
}
in getListLength im getting 3 when i print count before the return statement. But after the function returns I'm left with no output. I feel really stupid right now. Any thoughts?
Assuming this is the code from the quiz (argh, PHP4 --'):
class IntList{
var $value = 1;
var $next = null;
}
$A = new IntList();
$B = new IntList();
$C = new IntList();
$D = new IntList();
$A->next = $B;
$B->next = $C;
$C->next = $D;
I don't think you need recursion to solve that. You could just:
function getListLength($list) {
$count = 0;
$item = $list;
while($item instanceof IntList) {
$count++;
$item = $item->next;
}
return $count;
}
You just forgot to put global $count; in the second function.
Also, if you want to count the last one, you should move the $count++ outside of the conditional.
Here's a fiddle.
Alternatively, you can pass the $count variable by reference
function getListLength($L, &$count){...}
Another fiddle..
Since you are trying to use recursion here, I think the only thing that is missing is that your recursive case is not returning. You really should not need global. If you need to start at zero, you can give your getListLength a default count, or explicitly call it with zero in main.
function main($L) {
$final = getListLength($L);
print $final;
}
function getListLength($L, $count = 0) {
if (isset($L->next)) {
$count++;
// this case should return
return getListLength($L->next, $count);
} else {
return $count;
}
}

PHP, How can I sum-up the numeric values after calling a function from within a class?

The program deals 5 cards to each player displaying images of the cards along with the cards number value, after user selects number of players.
Everything works as described above, but I don't know how to total the values after calling the function. Can anyone give me an idea?
<?php
class classHand
{
var $totals;
var $cards;
function drawCard($c, $theDeck)
{
if (is_numeric($c)) {
$c = floor($c);
for ($i = 0; $i < $c; $i++) {
$this->cards[] = $theDeck->dealCard();
}
}
}
function showHand()
{
print("<table border=0>\n");
print("<tr><td> </td>\n");
for ($i = 0; $i < count($this->cards); $i++) {
print("<td>" . $this->cards[$i]->getImage() . "</td><td> </td>\n");
}
print("</tr></table>\n");
}
function showValue()
{
for ($i = 0; $i < count($this->cards); $i++) {
print(" " . $this->cards[$i]->getValue() . " ");
}
} // end of showValue
} // end of classHand
class classPlayer
{
var $name;
var $hand;
function classPlayer($n = "player")
{
$this->name = $n;
$this->hand = new classHand();
}
}
Then this is the page that implements the classes called cards.php
<?php
include("classCard.php");
$dealersDeck = new classDeck();
$dealersDeck->shuffleDeck();
$player[] = new classPlayer("You");
$selected_players = $_POST['players'];
for ($i = 0; $i < 5; $i++) {
for ($j = 0; $j < count($player); $j++) {
$player[$j]->hand->drawCard(1, $dealersDeck);
}
}
for ($i = 0; $i < count($player); $i++) {
print("Player: " . $player[$i]->name . "<br />");
$player[$i]->hand->showHand();
$player[$i]->hand->showValue();
print("<P> </p>");
}
Your $totals property wasn't used, so I renamed it to $totalValue. In this variable, you keep track of the cards in the hand.
class Hand
{
protected $totalValue;
protected $cards;
public function __construct()
{
$this->reset();
}
/**
* $deck is the only required parameter
*/
public function drawCard($deck, $count = 1, $reset = false)
{
// reset the counter
$this->reset();
if (!is_numeric($count)) return;
for ($i = 0; $i < $ccount; $i++) {
$this->addCard($deck->dealCard());
}
}
public function addCard(Card $card)
{
$this->totalValue += $card->getValue();
$this->cards[] = $card;
}
function getTotalValue()
{
return $this->totalValue;
}
public function reset()
{
$this->totalValue = 0;
$this->cards = array();
}
}
Now you can get the value of the Hand:
$deck = new Deck();
$players[] = new Player("You");
// start with 5 cards
foreach ($players as $player) {
$player->getHand()->drawCard($deck, 5);
}
// each player draws a card
foreach ($players as $player) {
$player->getHand()->drawCard($deck);
}
// get totals
foreach ($players as $player) {
print("Player: " . $player->getName() . "<br />");
$player->getHand()->getTotalValue();
print("<P> </p>");
}
// start again with new 5 cards
foreach ($players as $player) {
$player->getHand()->drawCard($deck, 5, true); // reseting with the 3rd param
}
You don't need to prefix your class names with class, and public properties are considered "not done". Normal practice is to set all properties to protected at minimum, and add accessor functions (get..() and set...())
And in this particular example, I would even consider merging the Player and Hand classes, because they kind of resemble the same thing. Unless the Player object is a generic user object you will reuse in many places of course.
function drawCard($c,$theDeck){
if(is_numeric($c)){
$c=floor($c);
for($i=0;$i<$c;$i++){
$this->cards[] = $theDeck->dealCard();
$this->total += $theDeck->dealCard()->getValue();
}
}
}
function getTotal(){
return $this->total;
}

Categories