How can i update or insert compare two fields from database - php

I want to compare either mobile or email fields exists in database it should update row else insert row
$ref = Ref::updateOrCreate(
[
'mobile' => $request['mobile'],
'email' => $request['email_address']
],
[
'firstname' => $request['firstname'],
"lastname" => $request['lastname'],
"mobile" => $request['mobile'],
"email" => $request['email_address'],
"mobile_verified" => $req->session()->get('mobile_verified'),
"quiz_data" => $req->session()->get('quiz_data'),
"verification_token" => $req_token
]
);

Do like this
$result= DB::statement("INSERT INTO table_name
(firstname,lastname,mobile,email,mobile_verified,quiz_data,verification_token)
VALUES ('".$request['firstname']."','".$request['lastname']."','".$request['mobile']."','"
.$request['email_address']."','".$req->session()->get('mobile_verified')."','"
.$req->session()->get('quiz_data')."','".$req_token."',)
ON DUPLICATE KEY UPDATE mobile = VALUES(mobile),email = VALUES(email);");
Replace table_name with your table name and try .
Here your mobile and email will be updated if the data is present before.

There is no Laravel function to compare on either field, you will have to execute two queries manually.
// Find an existing Ref
$ref = Ref::where('mobile', $request['mobile'])
->orWhere('email', $request['email_address'])
->first();
// Test if exists
if (isset($ref))
{
$ref->update([
// Update fields
]);
}
else
{
$ref = Ref::create([
// Create fields
]);
}

Related

Laravel UpdateOrCreate To Be Different values on Create on Update

Is there something like UpdateOrCreate I can use to have different values on create and on update. Meaning if it’s updating i don’t want it to change a certain column but i want it to insert the first time.
eg
$person = ['name'=> 'John', 'age' => 6, 'joined' => '2017-01-01'];
If John exists update age. If it doesn’t insert age and joined;
People::updateOrCreate(
['name' => $person['name']],
['age' => $person['age'], 'joined' => $person['joined']]
)
will update joined every time and i don't wanna change it.
You can use updateOrNew which doesn't persist it to the database and then check if it is not already in the database you can change the property you want to change.
$record = People::updateOrNew(
['name' => $person['name']],
['age' => $person['age']]
);
if(!$record->exists()) {
$record->joined = $person['joined'];
}
$record->save();
But if you are only trying to get the record if it exists and create it if it doesn't, use firstOrCreate() instead. That won't affect existing records, only return them, and it will create the record if it doesn't exist.
There is no any other option else you can try following:
$person = People::where('name', $name)->first();
if (!is_null($person)) {
$person->update([
'age' => $age
]);
}else{
$person = People::create([
'name' => $name,
'age' => $age,
'joined' => date('Y-m-d')
]);
}

How to merge exists data with new data?

Method 1 : Here I wrote the code for insert booking seat data into the database
Problem : When I book new seat it will creating new row so I'm getting duplicate rows so I tried method 2
Method 1 code :
$booking = new Bookings();
$booking->users_id = 4;
$booking->schedules_id = $schedules_id;
$booking->buses_id = $buses_id;
$booking->routes_id = $routes_id;
$booking->seat = implode(',', $seat);
$booking->price = $request->price;
$booking->profile = 'pending';
Method 2 : Here checking schedules_id equal to exists schedules_id then update seat and other data's
Problem : Insert new data updating old data
Method 2 code :
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id], // match the row based on this array
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => json_encode($seat),
'price' => $request->price,
'profile' => 'pending',
]
);
// I don't know this is logically correct or wrong
My idea : Here I'm retrieving old data and storing into one variable then merging old data and new data into one column
Problem : Getting error.
My idea code :
$extSeat = DB::table('bookings')->select('seat')->get();
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat)),
'price' => $request->price,
'profile' => 'pending',
]);
what i actually need ? : i need merge exists data with new data without updating.
Old data look like A1,B1
when insert new data like C1
i need data like this A1,B1,C1
I hope I explain clear enough. Any help is appreciated, thank you.
I don't know this is a correct logic or not but works for me, any other suggestions are welcome.
$extSeat = DB::table('bookings')->select('seat')->first();
$extSeat = explode(",", $extSeat->seat);
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat )),
'price' => $request->price,
'profile' => 'pending',
]);

Distinct Values in Laravel

Hello Friends I am using the following query :
$cur_date = date('Y-m-d');
$clientTemp = DB::table('clients')->where('quotations.exp_date','<',$cur_date)
->join('quotations','quotations.customer_id','=','clients.id')
->get()
->map(function ($clientTemp) {
return [
'id' => $clientTemp->id,
'hash' => $clientTemp->hash,
'name' => $clientTemp->first_name.' '.$clientTemp->last_name,
'email' => $clientTemp->email,
'mobile' => $clientTemp->mobile
];
});
I am getting this data from two tables :
1. Qutoations and 2. Clients.
In quotations table if the exp_date is less than current date then the details will be fetched from client table.
But there is possibility then there are more than 1 rows in quotation table but I want to fetch only one table from that for which customer_id is unique. How can I fetch unique row with same customer_id from quotations table
You'd need to use a GROUP BY clause but due to MySQL's default ONLY_FULL_GROUP_BY mode, you must aggregate any column that has more than one value.
You don't seem to be actually using any values from quotations, so you could just add:
DB::table('clients')->select('clients.*')->groupBy('clients.id')...
Otherwise, you'd need to tell MySQL how to aggregate any rows that have multiple values, like:
DB::table('clients')->selectRaw('clients.*, MIN(quotations.id)')->groupBy('clients.id')...
You should use groupby
$cur_date = date('Y-m-d'); $clientTemp = DB::table('clients')->where('quotations.exp_date','<',$cur_date)
->join('quotations','quotations.customer_id','=','clients.id')
->->groupBy('quotations.customer_id')
->get()
->map(function ($clientTemp) {
return [
'id' => $clientTemp->id,
'hash' => $clientTemp->hash,
'name' => $clientTemp->first_name.' '.$clientTemp->last_name,
'email' => $clientTemp->email,
'mobile' => $clientTemp->mobile
];
});

Save all record records using request->all in Laravel

Laravel provides a great help for developers to save all input fields of a form which is one record with one line of code.
like if I want to save a form which has multiple input fields and one record to database like:
then I can save it with below code and it works great:
SaveOrder:: create($request->all());
Now I have a question. If I have multiple records (multiple rows) in a form and I can add new rows with a button pressed. Then how can I save all records with above code?
Like:
It's easy to do that using Eloquent :
$data = array(
array('field1'=>'value1', 'field2'=> value2),
array('field1'=>'value1', 'field2'=> value1),
//...
);
Model::insert($data);
Assuming your input names look something like name[], since you can add rows on the fly, you can retrieve the input as an array, and insert them using something like this:
$data = [];
$names = request('name');
$product_names = request('product_name');
$product_colour = request('product_colour');
$product_size = request('product_size');
for ($i = 0; $i < count($names); $i++) {
// Add checks to make sure indices actually exist, probably using preprocessing in JS
$data[] = [
'name' => $names[$i],
'product_name' => $product_names[$i],
'product_colour' => $product_colour[$i],
'product_size' => $product_size[$i],
];
}
Model::insert($data);
The best answer for this question is using foreach statement. Like:
$CustomerName= $request -> input('CustomerName');
$ProductId= $request -> input('ProductId');
$ProductName= $request -> input('ProductName');
$ProductColor= $request -> input('ProductColor');
foreach( $ProductId as $key => $n ) {
SaveOrder::insert(
array(
'CustomerName' => $CustomerName[$key],
'ProductId' => $ProductId[$key],
'ProductName' => $ProductPrice[$key],
'ProductColor' => $ProductQuantity[$key],
)
);}
Use upsert
If you use Laravel 8 or above, you can make use of upsert. Such an useful function to insert or update matching records at the same time.
SaveOrder::upsert($request->all(), ['id'], ['CustomerName', 'ProductName', 'ProductColor', 'ProductID']);
The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);
Read the documentation on Laravel Upsert

Insert jQuery repeater row in PHP database

I have 1 row having 5 form fields. User can add/remove rows. Its repeatable row.
Now i want to store these fields into database with PDO php.
For normal values i am using this code but i am confused for repeater field.
$data = array(
'bill_no' => trim($_REQUEST['bill_no']),
'from_name' => trim($_REQUEST['from_name']),
'to_name' => trim($_REQUEST['to_name']),
'date' => trim($_REQUEST['date_bill']),
'mr_or_ms' => trim($_REQUEST['mr_or_ms']),
);
if($crud->InsertData("bill",$data)) {
header("Location: add-bill.php");
}
Insert Function:
public function InsertData($table,$fields) {
$field = array_keys($fields);
$single_field = implode(",", $field);
$val = implode("','", $fields);
try {
$query = $this->db->prepare("INSERT INTO ".$table."(".$single_field.") VALUES('".$val."')");
$query->execute();
return true;
} catch(PDOException $e) {
echo "unable to insert data";
}
}
Please help me to insert fields. Thanks
Change the names of your form fields, add [] to the end to get PHP arrays. For example change bill_no to bill_no[]. Something like this:
foreach($_REQUEST['bill_no'] as $row_number => $row_content){
$data = array(
'bill_no' => trim($_REQUEST['bill_no'][$row_number]),
'from_name' => trim($_REQUEST['from_name'][$row_number]),
'to_name' => trim($_REQUEST['to_name'][$row_number]),
'date' => trim($_REQUEST['date_bill'][$row_number]),
'mr_or_ms' => trim($_REQUEST['mr_or_ms'][$row_number]),
);
$crud->InsertData("bill",$data);
}
This assumes the browser is not mixing up the order of the fields, so maybe it's better to add unique names to the form fields when adding rows.
Also, there's no input data validation at all, please ensure you are escaping all data properly.
I did it with this method.
$total=count($_POST['description']);
for($i=0; $i<$total; $i++){
$data1 = array(
'bill_no' => trim($_POST['bill_no']),
'description' => trim($_POST['description'][$i]),
'nos' => trim($_POST['nos'][$i]),
'nos_day' => trim($_POST['nos_day'][$i]),
'pay' => trim($_POST['pay'][$i]),
'weekly_off' => trim($_POST['weekly'][$i]),
'hra' => trim($_POST['hra'][$i]),
'rs' => trim($_POST['rs'][$i]),
'ps' => trim($_POST['ps'][$i]),
);
$crud->InsertData("bill_details",$data1);
}

Categories