updateOrcreate() record new data when i update existing data - laravel

I want to use method updateOrcreate(), when data is an empty new record to the database, but when data is existing is updated data,
like image bellow data is empty I want to record new data to database
like image bellow data is existing I want to update existing data and record to database
this is my code
public function simpanDataUn(Request $request)
{
$mapel_ujian_id = $request->mapel_ujian_id;
for($i=0; $i < count($mapel_ujian_id); $i++)
{
$arr = NilaiUjianAKhir::updateOrCreate([
'sekolah_id' => \Auth::user()->sekolah_id,
'siswa_id' => $request->id,
'mapel_ujian_id' => $request->mapel_ujian_id[$i],
'nilai_standar_daerah' => $request->nilai_standar_daerah[$i],
'predikat_standar_daerah' => $request->predikat_standar_daerah[$i],
'nilai_sekolah' => $request->nillai_sekolah[$i],
'predikat_nilai_sekolah' => $request->predikat_nillai_sekolah[$i],
'nilai_akhir' => $request->nilai_akhir[$i],
'predikat_nilai_akhir' => $request->predikat_nilai_akhir[$i],
],
[
'nilai_standar_daerah' => $request->nilai_standar_daerah[$i],
'predikat_standar_daerah' => $request->predikat_standar_daerah[$i],
'nilai_sekolah' => $request->nillai_sekolah[$i],
'predikat_nilai_sekolah' => $request->predikat_nillai_sekolah[$i],
'nilai_akhir' => $request->nilai_akhir[$i],
'predikat_nilai_akhir' => $request->predikat_nilai_akhir[$i],
]);
}
return redirect()->back()->with('success', 'Data UN berhasil di input');
}
I'm using updateOrCreate()method, but when i UPDATED existing data, the data
and even create new data, not updated existing data, like image below:
What part is wrong from my code? how to updated existing data using updateOrCreate() method?
please help me, thanks

Maybe you can change your code like this :
public function simpanDataUn(Request $request)
{
$mapel_ujian_id = $request->mapel_ujian_id;
for($i=0; $i < count($mapel_ujian_id); $i++)
{
$arr = NilaiUjianAKhir::updateOrCreate([
'sekolah_id' => \Auth::user()->sekolah_id,
'siswa_id' => $request->id,
'mapel_ujian_id' => $request->mapel_ujian_id[$i],
],
[
'nilai_standar_daerah' => $request->nilai_standar_daerah[$i],
'predikat_standar_daerah' => $request->predikat_standar_daerah[$i],
'nilai_sekolah' => $request->nillai_sekolah[$i],
'predikat_nilai_sekolah' => $request->predikat_nillai_sekolah[$i],
'nilai_akhir' => $request->nilai_akhir[$i],
'predikat_nilai_akhir' => $request->predikat_nilai_akhir[$i],
]);
}
return redirect()->back()->with('success', 'Data UN berhasil di input');
}
Like #lagbox say the first array passed to updateOrCreate are the where conditions to find a record ... if it can't find a record by those conditions it will create a new one. You won't create the new one when there's same sekolah_id, siswa_id or mapel_ujian_id right? Then the other field can be updated

Related

Laravel Validating An Array in Update Method unique filter

I am new to Laravel. I try to validate an array in Laravel 9.
for using a unique filter I have a problem.
at first, I try to use this way
$rules = [
'*.id' => 'integer|required',
'*.key' => 'string|unique.settings|max:255|required',
'*.value' => 'array|nullable|max:255',
];
For the Create method, this works, but for updating, the logic is wrong. I need to ignore the current field.
for the update, I try to use this way
private function update(): array
{
foreach ($this->request->all() as $keys => $values) {
// dd($values['id']);
$rules[$keys .'.id' ] = 'integer|required';
$rules[$keys .'.key'] = ['string|max:255|required', Rule::unique('settings', 'key')->ignore($values['id'])];
$rules[$keys .'.value'] = 'array|nullable|max:255';
}
// dd($rules);
return $rules;
}
I got this error
BadMethodCallException: Method Illuminate\Validation\Validator::validateString|max does not exist. in file /Users/mortezashabani/code/accounting/vendor/laravel/framework/src/Illuminate/Validation/Validator.php on line 1534
how can I validate an array in the update method in Laravel 9?
PS: without Rule::unique('settings','key')->ignore($values['id'])] all filter is works without any problem
hello you can try this code in your function
$validated = $request->validate([
'id' => 'required',
'key' => 'string|unique.settings|max:255|required',
'value' => 'array|nullable|max:255',
]);

Why stored duplicate rows to table

I have custom query for adding parsed remote posts to table:
foreach ($parsedPosts as $post) {
$hasRemotePostAlready = Post::where('remote_post_id', $post->id)->first();
if(null === $hasRemotePostAlready) {
$data = [
'title' => $post->title,
'description' => $post->description,
'remote_post_id' => $post->id
];
Post::create($data);
}
}
Variable $parsedPosts has more then 3500 posts and when I run my script to add posts then any remote posts duplicated. Why they posts duplicated and why not work my condition:
$hasRemotePostAlready = Post::where('remote_post_id', $post->id)->first();
How I can fix duplicating rows problem in my case?
You can use firstOrCreate or updateOrCreate methods for this case, take a look at the documentation
In your case try this:
$hasRemotePostAlready = Post::firstOrCreate(
[
'remote_post_id' => $post->id // columns to check if record exists
],
[
'title' => $post->title,
'description' => $post->description
]
);

Inserting and updating records from 3 tables in laravel

I am storing records for my product transfer app using 3 tables in single action. Transferhistories, Warehouse1StockSummaries and Warehouse2StockSummaries.
storing records to trasnferinghistories is ok, and also the increment method I declare to Warehouse2StockSummaries is also working fine except for Warehouse1StockSummaries.
here's my store function,
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i<= count($input['product_id']); $i++) {
// if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
if(!isset($input['qty_in'][$i]) || !is_numeric($input['qty_in'][$i])) continue;
$acceptItem = [
'product_id' => $input['product_id'][$i],
'transfer_qty' => $input['qty_out'][$i],
'user_id' => $input['user_id'][$i]
];
array_push($items, Transferhistories::create($acceptItem));
// dd($input);
//update warehouse 1 summary
$warehouse1summary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if (!$warehouse1summary->wasRecentlyCreated) {
$warehouse1summary->increment('qty_out', $input['qty_out'][$i]);
}
//update warehouse 2 summary
$stock2Summary = Warehouse2StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_out'][$i],'qty_out' => null]);
if (!$stock2Summary->wasRecentlyCreated) {
$stock2Summary->increment('qty_in', $input['qty_in'][$i]);
}
}
return redirect()->route('transferHistory.index');
}
updating warehouse 1 summary is not doing what it should be.
any suggestion master? thank you so much in advance!
According to laravel, firstOrCreate does not save the value, so after you do:
$warehouse1summary = Warehouse1StockSummaries::updateOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
Edit
The method firstOrNew will return the first or a instance of the Model.
So what you wanna do is this:
$warehouse1summary = Warehouse1StockSummaries::firstOrNew(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if(isset($warehouse1summary->created_at)){
$warehouse1summary->qty_out = $warehouse1summary->qty_out + $input['qty_out'][$i];
}
$warehouse1summary->save();

Import CSV Using Laravel Excel (Maat)

Hi I have an excel file with the details of passengers under the trip ID. I want to import that excel file in my table. please see the picture below:
the first row with the blue color is my column names on my table. my problem is how can I save the value of D2:G2 in next_of_kin table with this kind of format.
[
{"name":James Lara,"mobile":12345678},
{"name":Jasmine Lara,"mobile":12345678}
]
this is my code on my controller.
// Get excel file
$path = $request->file;
// Save the content to passenger
Excel::load($path, function ($reader) use ($request) {
$trip = Trip::where('id', $request->trip_customer_id)->first();
foreach ($reader->toArray() as $row) {
$trip->passengers()->create($row);
}
});
on my foreach inside the controller this looks like.
foreach ($reader->toArray() as $row) {
$given_name = array(
['name' =>$row['nok_one'],'mobile' => $row['nok_one_mobile']],
['name' =>$row['nok_two'],'mobile' => $row['nok_two_mobile']]
);
$trip->passengers()->create([
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'next_of_kin' => $given_name
]);
}

Laravel UpdateOR Create not work with relationship

I want to update my related table on laravel 5.4
my code
$id = $request->id;
$find = Presal::find($id);
$find->user_id = $request->customer_id;
$find->proposalid = $request->proposalid;
$psal = $find->save();
if ($psal) {
foreach ($request->service_item_id as $key => $n) {
$find->proposalService()->updateOrCreate([
'service_item_id' => $request->service_item_id[$key],
'start_date' => $request->start_date[$key],
'end_date' => $request->end_date[$key],
'service_type_id' => $request->service_type_id[$key],
'vendor_submit' => $request->vendor_submit[$key],
]);
}
}
Here always my code create a new row in proposalService but not update.
How can I make create if new and Update if exist.
updateOrCreate() takes 2 arguments (2 arrays). First array, you pass the element you want to check, usually the primary key and some other element. It then checks if those elements exist, else, create a new one.
$find->proposalService()->updateOrCreate(
[
'service_item_id' => $request->service_item_id[$key],
'service_type_id' => $request->service_type_id[$key]
],
[
'start_date' => $request->start_date[$key],
'end_date' => $request->end_date[$key],
'vendor_submit' => $request->vendor_submit[$key]
]
);
Here I used service_item_id and service_type_id as first argument to check if they already exist.

Resources