php+laravel , quantity get back - php

I have 3 tables (sales, sales_detail, and bicycle). I don't know how to get back my quantity (sales) to unit balance (bicycle) and then delete the sales_detail entry because I'm going to update new sales.
public function edit(Request $request, $id) {
$sales = Sales::find($id);
$sales_details = SalesDetail::where('sales_id', $id)->get();
$bicycles = Bicycle::where('sales_id', $id)->get();
foreach ($bicycles as $bc && $sales_details as $sd) {
$bc->unit_balance = $sd->quantity + $bc->unit_balance;
//then delete sales_detail
}
return view('sales/edit', array(
'sales' => $sales,
'sales_details' => $sales_details,
'bicycles' => $bicycles
));
}

I suggest the use of Elequents relations in your Models such as 'belongsto' and 'hasmany' to better prepare data. Following this practice would allow you to simplify your queries during development. Your approach is very messy/novice and procedural.
Checkout https://laravel.com/docs/5.8/eloquent-relationships

public function edit(Request $request, $id) {
$sales = Sales::find($id); // get sales where sales_id = 40
$sales_details = SalesDetail::where('sales_id', $id)->get();
return view('sales/edit', array( 'sales' => $sales,
'sales_details' => $sales_details ));
}
public function update(Request $request, $id) {
$sales = Sales::find($id);
$sales_details = SalesDetail::where('sales_id',$id)->get();
foreach ($sales_details as $sales_dtl) {
$bicycle = Bicycle::find($sales_dtl->bicycle_id);
$bicycle->unit_balance = $bicycle->unit_balance + $sales_dtl['quantity'];
$bicycle->save();
$sales_dtl->delete();
}
$this->saveData($sales,$request);
return redirect()->route('sales.index');
}
i get my answer already

Related

How to loop foreach in laravel dynamically

Am just learning Laravel and I have this logic were in I want to display array of total items based from user, to explain this further here is my database
user table
items table
this is my current code
public function display()
{
$users = User::where('type', 'Shop')->get();
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
}
$total = Item::where('user_id', $shop_id)->sum('total');
$shops =[
['Name' => $shop_name, 'total' => $total],
];
return response()->json([
"shops" =>$shops
], 200);
}
and here is my sample output:
am only getting 1 object instead of 2 as I have two shops how to loop this dynamically.
thanks
the $shops and $total variable is not in foreach loop that's because it returns only one row. and you must use $shops[] .
public function display()
{
$users = User::where('type', 'Shop')->get();
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
$total = Item::where('user_id', $shop_id)->sum('total');
$shops[] =['Name' => $shop_name, 'total' => $total];
}
return response()->json([
"shops" =>$shops
], 200);
}
but the best and clean way is to use laravel relationship
in User model:
public function items()
{
return $this->hasMany(Item::class) ;
}
and display controller :
public function display()
{
$shops = User::where('type', 'Shop')->get()
->mapWithKeys(function($user){
return ['name'=>$user->name ,
'total'=> $user->items->sum('total')
]});
return response()->json(["shops" =>$shops], 200);
}
Do this
$shops[] = ['Name' => $shop_name, 'total' => $total];
to push all the shops into one array.
You are currently overriding the hole array.
UPDATE: Also move the sql part into the foreach:
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
$total = Item::where('user_id', $shop_id)->sum('total');
$shops[] =['Name' => $shop_name, 'total' => $total];
}

Sort by relationship first in laravel

I have two tables: admins and log_doctor_infos. admins table has relationship hasOne with log_doctor_infos throught doctor_id like this.
In model Admin:
public function logDoctorInfo() {
return $this->hasOne(LogDoctorInfo::class, 'doctor_id', 'id');
// Model LogDoctorInfo is log_doctor_infos table
}
And in Model LogDoctorInfo:
public function doctor(){
return $this->belongsTo(Admin::class, 'doctor_id', 'id');
// Model Admin is admins table
}
I get all data form admins table and i want to sort record has relationship with log_doctor_infos to top.
Yellow record, which has relationship with log_doctor_infos and i want to sort it in top.
Edit: i use paginate in this query and i really want to get quantity of Yellow record.
Thanks for reading!
In my controller, i have custom filter and paginate. Help me.
public function index(Request $request) {
$fullname = $request->query('fullname', NULL);
$phone = $request->query('phone', NULL);
$status = $request->query('status', NULL);
$doctors = (new Doctor)->newQuery();
if ($fullname != NULL) {
$doctors = $doctors->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone != NULL) {
$doctors = $doctors->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status != NULL) {
$doctors = $doctors->where('status', $status);
}
$doctors = $doctors
// ->with(array('logDoctorInfo' => function($query) {
// $query->orderBy('updated_at', 'ASC');
// }))
->latest()
->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
you can use the withCount method.
Admin::withCount('logDoctorInfo')
->orderBy('log_doctor_info_count', 'desc')
->paginate(5);
Your controller will look like this
public function index(Request $request) {
$fullname = $request->input('fullname', NULL);
$phone = $request->input('phone', NULL);
$status = $request->input('status', NULL);
$doctorQuery = Doctor::query();
if ($fullname) {
$doctorQuery->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone) {
$doctorQuery->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status) {
$doctorQuery->where('status', $status);
}
$doctorQuery->withCount('logDoctorInfo')
->orderBy('log_doctor_info_count');
$doctors = $doctorQuery->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
Doctor::with('logDoctorInfo')->get()->sortByDesc('logDoctorInfo.id');

Laravel Increase SQL speed

I am trying to increase the speed of my queries in Laravel 5.7 and I have the call down to ~2.5 seconds. I am trying to figure out more ways to make it faster and if I could get some help I'd greatly appreciate it.
Thanks
How my data is structured:
Function(Controller):
public function getUserDataTmp(Request $request) {
$input = file_get_contents("php://input");
$request = json_decode($input);
if ($this->authTokenAccess($request) == true) {
$bottomWords = bottom_exterior_word::select('word','sentence','sequence','id','group_id')->where('user_id','=', $request->id)->get();
$emergencyWords = left_exterior_word::select('word','sentence','sequence','id')->where('user_id','=', $request->id)->get();
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
$data = [
'data' => [
'return' => 'success',
'code' => 'VEDC001',
'response' => 'Successfully Gathered Words',
'main_categories' => $bottomWords,
'emergency_words' => $emergencyWords
]
];
return(json_encode($data));
}
}
getMainWords Function(bottom_exterior_word model):
public function getMainWords($group_id, $id)
{
// return("TEST");
$words = \App\main_word::select('id','group_id','sentence','sequence','word')->where('group_id','=', $group_id)->where('user_id','=', $id)->get();
foreach ($words as $key => $word) {
$words[$key]->image = Image::select('base64','id')->where('word_id','=', $word->id)->first();
}
return $words;
}
Start by refactoring so that you dont query inside a foreach loop
foreach($bottomWords as $tmp => $key) {
$group_id = $key->group_id;
$bottomWords->user_id = $request->id;
$bottomWords[$tmp]->words = $key->getMainWords($group_id, $request->id);
}
I would change the getMainWords function to accepts an array of group id's and use the whereIn clause:
The whereIn method verifies that a given column's value is contained
within the given array:
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
Same treatment for this loop.
foreach($emergencyWords as $key => $word) {
$emergencyWords[$key]->image = imageModel::select('base64','id')->where('emergency_id','=', $word->id)->first();
}
In general minimizing the NUMBER of queries will improve response time.
Old post, would just like to update it though. Since I have first posted this, I have learned a lot more about Laravel and am a lot more experienced with it.
Here is my new function and solution:
Controller:
public function data(Request $request)
{
return response()->success(
[
'emergencywords' => EmergencyWord::with('image')->whereUserId($request->user()->id)->get(),
'categorywords' => CategoryWord::with(['image','words.image'])->whereUserId($request->user()->id)->get(),
]
);
}
Category Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
public function words()
{
return $this->hasMany('App\MainWord','category_words_id','sequence');
}
Emergency Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}
Main Word Relationships:
public function image()
{
return $this->hasOne('App\Image','id','image_id');
}

Updating Pivot table in laravel

i have services and items table. i have the pivot table as service_item. I am able to store data into my pivot table however i can't get the right syntax to update the pivot table. My code stores a new data when i try to update an existing data.
PS: My code although is able to edit the client's name but not the items that the client bought earlier.
I want to be able to update the item_id and quantity
service_item - pivot.
service_id
item_id
qty
Controller
public function store(Request $request)
{
$service = new Service(array(
'id' => $service_no,
));
$service->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->attach($selectedItems);
}
public function update($id, Request $request)
{
$service = Service::findOrFail($id);
$service->clients->name = $request->get('name');
$service->clients->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->attach($selectedItems);
}
Okay after researching, i was able to solve this using updateExistingPivot
public function update($id, Request $request)
{
$service = Service::findOrFail($id);
$service->clients->name = $request->get('name');
$service->clients->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->updateExistingPivot($item_id, ['quantity' => selectedItems], false);
}

how can I get price cart from database in Code Igniter

it's my controller
function set_hargabesar($id){
$this->load->library('cart');
$condition['id'] = 'id';
$get = $this->myigniter_model->getharga('harga_satuan','id');
$data = array(
'rowid' => $id,
'qty' => 5,
'price' => $get,
);
$this->cart->update_all($data);
}
it's my model
public function getharga($harga, $id){
$this->db->select($harga);
$this->db->from('barang');
$this->db->where('id',$id);
$query=$this->db->get();
}
How can I get a 'harga_satuan' (price cart) from database
please help me.
I can get the data(harga_satuan) from database with this code.
You've only executed your query, you need to retrieve data.
Model:
public function getharga($harga, $id){
$this->db->select($harga);
$this->db->from('barang');
$this->db->where('id',$id);
$query=$this->db->get();
$row = $query->row_array();
return $row;
}
In your controller just change this:
'price' => $get['harga_satuan'],
And, of course, you need to pass id to your model:
$get = $this->myigniter_model->getharga('harga_satuan', $id);
(but I hope you are doing it)

Categories