Laravel model is updating multiple models instead of single - laravel

I am trying to update my model using multiple where conditions.
my code is
public function UpdateEducationData(Request $request)
{
$user = app('user');
// return $request;
$education = eduinfo::where("id", $user->id)->where("exam", $request->type)->first();
// dump sql query for debugging
// $education->rawSql();
// dd($education);
$education->board = $request->board;
// $education->degree = $request->degree;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
// update education based on exam
$education->save();
return redirect()->back()->with("message", "Education Information Updated Successfully");
return "Update Education Data";
}
My code is updating a eduinfo table based on id and exam. But whenever this function is called it updates all eduinfo records related to that user id.
I tried to update eduinfo table single record but multiple records are being update at once. I dumped eduinfo after retriving the model and yes it's retrieving the single model using first() method but still when save() is called it updates all records of that user id in eduinfo.

I think Your conditions to make a unique record are not.
But if you wanna Just run one time! I have an offer to you.
$flag=true;
if($flag){
$user = \Auth::user();
$education = eduinfo::where('id','=', $user->id)->where('exam','=', $request->type)->first();
$education->board = $request->board;
$education->year = $request->year;
$education->rollno = $request->rollno;
$education->obtainmarks = $request->obtainmarks;
$education->totalmarks = $request->totalmarks;
$education->division = $request->division;
$education->grade = $request->grade;
$education->totalcgpa = $request->totalcgpa;
$education->obtailcgpa = $request->obtailcgpa;
$education->save();
$flag=false;
}
It's depends on my answer.

Related

I want to retrieve the id from the query result and reuse it for the next query laravel

I want to use the id from the select query results, then I want to use that id again to find data using wherein. but the error i found,
public function getMaut(){
$merek="samsung";
$tipe="led TV";
$display ="25-32";
$kriteria=Kriteria::all();
$alternatif = Alternatif::where('merek',$merek)->where('tipe',$tipe)->where('display',$display)->get();
$alternatif_id = (array)$alternatif->id;
$nilaialter = Nilaialternatif::whereIn('id_alternatifs',$alternatif_id);
return view('spk.index',compact('kriteria','alternatif','nilaialter','alternatif_id'));
}
Use the pluck method to retrieve all values for a given key.
$alternatif = Alternatif::where('merek', $merek)->where('tipe', $tipe)->where('display', $display)->get();
$alternatif_id = $alternatif->pluck('id');
$nilaialter = Nilaialternatif::whereIn('id_alternatifs', $alternatif_id)->get();
Alternatively, you can create a hasMany relation to 'Nilaialternatif' at 'Alternatif' model.
class Alternatif extends Model
{
public function nilaialternatifs()
{
return $this->hasMany(Nilaialternatif::class, 'id_alternatifs');
}
}
Then query the relationship like
$alternatif = Alternatif::with('nilaialternatifs')->where('merek', $merek)->where('tipe', $tipe)->where('display', $display)->get();
$nilaialter = $alternatif->nilaialternatifs;
$nilaialter = [];
$alternatif = Alternatif::where('merek', $merek)->where('tipe', $tipe)->where('display', $display)->get()->toArray();
if (count($alternatif)) {
$alternatif_ids = collect($alternatif)->pluck('id')->toArray();
$nilaialter = Nilaialternatif::whereIn('id_alternatifs', $alternatif_ids)->get()->toArray();
}
use laravel collection, https://laravel.com/docs/6.x/collections
use pluck method of collection,https://laravel.com/docs/6.x/collections#method-pluck

How to update a row from a different row data using laravel

By clicking verify button I want the status of payment to change from pending to verified, then the pending amount (in payments table) to sum up with the wallet balance amount in users table and the final balance updated in users table using Laravel. This is my controller. Please help
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
return redirect()->route('all.payments');
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return back();
}
public function verify_payment($user_id,$payment_data,$id){
$wallet = Mpesa::findOrFail($id);
$wallet->status = 'verified';
if($wallet->save()){
flash(__('Payment has been approved successfully'))->success();
}
$top_up = User::findOrFail($user_id);
$top_up->amount = $payment_data['amount'];
$top_up->balance = $top_up->balance + $payment_data['amount'];
$top_up->save();
flash(__('Something went wrong'))->error();
return redirect()->route('all.payments');
}

Fetch data from a 2 many to many table

I am using codeigniter activerecord and I am fetching information of 2 many to many table but undefined index is appearing in my error log in the CI view
public function editCommission($data){
$this->db->select('client_user_cashin.id, client.account_name, property.property_name, client.unit_number, client.reservation_date, users.givenname, users.surname, client_user.sl_rate, sl_position.position, cash_in.cash_recieved, comm_status.comm_status, computation_type.com_type');
$this->db->from('client_user_cashin');
$this->db->join('client_user', 'client_user.id = client_user_cashin.client_user_id');
$this->db->join('client', 'client.id = client_user.client_id');
$this->db->join('property_commision', 'property_commision.id = client.property_commision_id');
$this->db->join('property', 'property.id = client.property_id');
$this->db->join('users', 'users.id = client_user.user_id');
$this->db->join('sl_position', 'sl_position.id = client_user.sl_position_id');
$this->db->join('cash_in', 'cash_in.id = client_user_cashin.cash_in_id');
$this->db->join('comm_status', 'comm_status.id = client_user_cashin.comm_status_id');
$this->db->join('computation_type', 'computation_type.id = cash_in.comp_type_id');
$this->db->order_by('client_user_cashin.id');
$query = $this->db->get();
return $query->result_array();
}
Fetch the data in the edit form
Just apply left-join on all the joins like
$this->db->join('client_user', 'client_user.id = client_user_cashin.client_user_id','left');

carregar mĂșltiplos modelos em um controller

In my Create function, from my products controller. I make several calls to other models that are used to mount combos on the view blade.
$grade = Grade::all();
$marca = Marca::all();
$ncm = Ncm::all();
$clafiscal = Clafiscal::all();
$Otributaria = Origemtributaria::all();
$unidade = Unidade::all();
...
return view('products.create',
compact(
'page',
'etiqueta',
'compCusto',
'grade',
'marca',
'ncm' ,
'clafiscal',
'Otributaria',
'grupo',
'colecao'...);
Is it possible for me to reduce these calls?
I believe there is no other way to compact multiple values.
But, if your problem is related to the dirty controller (with many function calls and responsibilities), you should try to create a more specific method, with will handle this dependencies load and dependencies compact.
Try something like this:
public function loadDependencies()
{
$dependencias = [];
$dependencias['grade'] = Grade::all();
$dependencias['marca'] = Marca::all();
$dependencias['ncm'] = Ncm::all();
$dependencias['clafiscal'] = Clafiscal::all();
$dependencias['Otributaria'] = Origemtributaria::all();
$dependencias['unidade'] = Unidade::all();
return compact($dependencias);
}
public function create()
{
return view('products.create', $this->loadDependencies());
}

How many times the query will hit the database?

Can any one plz optimize the below linq query.It should hit the database only once.
List<LearningItem> items = this.learningitemRepository.GetAll().ToList();
var model = new List<StatementViewerModel>();
foreach (var statement in subjects)
{
var mi = new StatementViewerModel();
mi.UserName = statement.UserName;
mi.SubjectName = statement.Name;
**int nofItems = items.Where(x => x.SubjectId == statement.SubjectId).Count();**
double ratio = (double)statement.AttendedItems / (double)nofItems;
int subjectprogress = (int)(ratio * 100);
mi.Progress = subjectprogress;
model.Add(mi);
}
From what you have posted, your Database should only be being accessed through the GetAll() method of your learmingitemRepository. So if you are worried that you are querying the Database more than once, the GetAll() function is where you should look (assuming your example is not in a function that is being repeatedly called itself).
The rest of your code is iterating over your subjects collection and adding objects to your model collection. There does not appear to be anything in the foreach loop that is accessing your Database.

Resources