Update database using foreach in laravel - php

I want to insert new data in database using API, but first, i want to check the database using $po_transaction, it exist or not, if $po_transaction exist, do updated. But when i am input same data, it changed all data with one value
This is my database, when first insert:
and this is my database, when i am input same data (This the issue):
This is my controller:
public function post_data(Request $request){
$po_transaction = $request->input('po_transaction');
$data = $request->input('data');
$decode_data = json_decode($data);
if(!$decode_data){
return response()->json(['message'=>'No Data','success'=>0]);
}
$po_id = Produk::where('po_transaction','=', $po_transaction)->first();
// if po_id exist, update the data
if ($po_id) {
foreach ($decode_data as $item => $value) {
DB::table('produk')
->where('po_transaction', $po_transaction)
->update(['po_transaction'=>$po_transaction, 'nama_produk'=>$value->produk, 'harga_jual'=>$value->price]);
}
return response()->json(['message'=>'success, data saved','success'=>1]);
}else{
// if po_id not exist, create new
foreach($decode_data as $item => $value)
{
$saveTransaction = new Produk();
$saveTransaction->po_transaction = $po_transaction;
$saveTransaction->nama_produk = $value->produk;
$saveTransaction->harga_jual = $value->price;
$saveTransaction->save();
}
if($saveTransaction->save()){
return response()->json(['message'=>'success, data saved','success'=>1]);
}else{
return response()->json(['message'=>'no data saved','success'=>0]);
}
}
}
and for data, i am using json data like this:
[
{"produk":"shampoo","price":"12000"},
{"produk":"noodle","price":"110200"},
{"produk":"cup","price":"1000"}
]
This is decode_data:
How to fix this issue, when i input same data, it not only change all data with one value?

You need to specify which record you actually want to update by proving the id in the where clause like this:
DB::table('produk')
->where([
'po_transaction' => $po_transaction,
'id_produk'=> $value->id,
])
->update([
'po_transaction'=>$po_transaction,
'nama_produk'=>$value->produk,
'harga_jual'=>$value->price,
]);

You can use this method <model_name>::updateOrCreate() to Create/Update in single method.
Produk::updateOrCreate(['po_transaction'=>$po_transaction,'nama_produk'=>$value->produk],['harga_jual'=>$value->price]);
for more info look at this https://laravel.com/docs/5.7/eloquent

Related

How to check duplicate title and not save to database in laravel

i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}

Update multiple ids against single id (Laravel)

I want to update multiple Departments against one unit. I tried this method, but it's not correct.
How can I update multiple departments ids?
Form:
Request:
Controller Function:
$pre_data = UnitDepartment::where('unit_id', $request->id)->get();
if ($pre_data) {
foreach ($pre_data as $value) {
$value->delete();
}
$department = $request->department_id;
foreach ($department as $value) {
$unitDepart = new UnitDepartment();
$unitDepart->unit_id = $request->id;
$unitDepart->department_id = $value;
$unitDepart->save();
}
}
table:
I found that is the table related to departments and units.
So you can build the relationship many-to-many between them,
Create the relationship in your models,
In Unit model:
public function departments()
{
return $this->belongsToMany('App\Unit','unit_department','unit_id','department_id');
}
In Department Model:
public function units()
{
return $this->belongsToMany('App\Department','unit_department','department_id','unit_id');
}
Attach the new relationship, simply use:
Unit::find($request->unit_id)->departments()
->sync($request->department_id);
Unfortunately, you cannot use softDelete on sync().
And I don't think you need to soft delete with unit_departments. As a pivot then it should be irrelevant if it is deleted or not.
And if user update the relationship on the frequent, this table will grow fast.
If you really need to soft-delete, you can write it like this:
$department_ids = $request->department_id;
$unit_id = $request->unit_id
// soft delete the unit_departments not in request:
UnitDepartment::where('unit_id', $unit_id)->whereNotIn('department_id', $department_ids)->delete();
// insert the new department_id+unit_id relationship
$exist_department_ids = UnitDepartment::where('unit_id', $unit_id)->whereIn('department_id', $department_ids)->pluck('department_ids')->all();
$dept_ids = array_diff($exist_department_ids, $department_ids);
$depts = collect($dept_ids)->map(function($dept_id) use ($unit_id) {
return ['department_id' => $dept_id, 'unit_id' => $unit_id];
});
UnitDepartment::insert($depts);
the problem is you're sending unit_id in the request, however using $request->id in the query which is wrong.
Change every occurance of $request->id with $request->unit_id in the controller.
to select pre data correctly
use
$pre_data = UnitDepartment::where('unit_id', $request->id)->first();
i tried this
$unit = UnitDepartment::where('unit_id', $request->unit_id)->get();
foreach ($unit as $item) {
$existDepartment[] = $item->department_id;
}
$newDepartment = $request->department_id;
$result = array_diff($newDepartment, $existDepartment);
if ($result) {
foreach ($result as $item) {
$data = new UnitDepartment();
$data->unit_id = $request->unit_id;
$data->department_id = $item;
$data->save();
}
}

$casts, array data

I'm using $casts to save data in array to database. I have an issue with that.
How can i push data to an existing array in the database?
For example i have already an array of data in my db column like: ["some_data", "another_el"] and so on and in the Controller i want to push in this array in db some other data from input.
$brand = Brand::find($request->input('brand'));
$brand->model = $request->input('model');
$brand->update();
Pushing data like this.
You cannot do this with Eloquent's Mass Assignment functions (update, create, etc). You must pull down your field, change it, then save the model.
$collection = collect($brand->field);
$collection->push($myNewData);
$brand->field = $collection->toJson();
$brand->save();
Way 1
$brand = Brand::find($request->input('brand'));
$brand->model = array_merge($brand->model, [$request->input('model')]);
$brand->update();
Way 2 (my favorite because it encapsulates the logic)
$brand = Brand::find($request->input('brand'));
$brand->addModel($request->input('model'));
$brand->update();
And on Entity:
public function addModel($value)
{
$this->model = array_merge($this->model, [$value]);
}
Optional
And on Entity (instead $casts):
public function setModelAttribute($value)
{
$this->attributes['model'] = json_encode($value);
}
public function getModelAttribute($value)
{
return json_decode($value, true);
}

how to insert array data in single column in mysql using codeigniter

I'm trying to insert array data into database using codeigniter. when I print that values using print_r() fun.
It shows correct result, but when I click on save button it inserts blank values in table.
I just want to store multiple medicine names in prescription table for particular prescription_id i am trying to insert data using insert_batch function but it saves blank records
this is my model code:
public function add_prescription($data) {
$data['medicine_name'] = $data['medicine_nm[]'];
print_r($data['medicine_name']);
$this->db->insert_batch('pre',$data);
return $this->db->insert_id($pre_id);
}
controller code--
public function prescription($patient_id = NULL, $app_date = NULL, $hour = NULL , $min = NULL) {
//Check if user has logged in
if (!$this->session->userdata('user_name') || $this->session->userdata('user_name') == '') {
redirect('login/index/');
} else {
if ($this->form_validation->run() === FALSE) {
$data['medicine_nm[]']=$this->input->post('medicine_nm[]');
$this->patient_model->add_prescription($data);
}
}
}
You need to json_encode that array and then insert it into the database like
$data = json_encode($array);
$this->db->insert('column_name',$data);
And while fetching you need to decode it
$data = json_decode($column_result);
Hope this helps you.
try this
public function add_prescription($name) {
$data = array(
'medicine_name' => $name
);
$query = $this->db->insert('table_name',$data);
return $query->result_array();
}
Hope this will help you

CakePhp does update instead of insert new data

i started using cakephp, but now i encountered a problem which i am not able to solve.
I have got the following model relations which are relevant:
Exercise hasMany Points
Student hasMany Points,
now i want to check in the studentsController if for every exercise there is a Point data set, and iff not insert a new one.
When starting with no Point datasets, the function adds a new Point dataset for the first exercise correct, but after this it only updates the erxercise_id of this dataset, instead of creating new ones.
The controller function looks like this:
public function correct($id = null) {
$this->Student->id = $id;
$this->Student->recursive = 2;
if ($this->request->is('get')) {
$data = $this->Student->Exam->Exercise->find('all');
foreach($data as $exercise)
{
$exerciseID = $exercise['Exercise']['id'];
$this->Student->Point->recursive = 0;
$foundPoints = $this->Student->Point->find('all', array('conditions' => array('exercise_id' => $exerciseID)));
if($foundPoints == null)
{
$emptyPoints = array ('Point' => array(
'exercise_id' => $exerciseID,
'student_id' => $id
)
);
$this->Student->Point->save($emptyPoints);
}
else{
}
}
}
else //POST
{
}
}
if you have to insert a data you to use create() method like this:
This is only an example, with this line you create every time a new record into your database
and save data
$this->Student->Point->create();
$this->Student->Point->save($emptyPoints);
$this->Student->Point->id = '';
$this->Student->Point->save($emptyPoints);
or
$this->Student->Point->saveAll($emptyPoints);

Categories