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];
}
Related
I'm having one more problem in the logical realm.
I have an array containing ids:
$product_ids = ['1', '5', '3']; <- Example
Another string that I convert to an array separating it by commas, this to indicate the quantities of the products to be withdrawn. For example for product 1 I want 3 drives so I would need the array element to be "1,3".
$finalarray = ["1,3", "5,2", "3,10"];
Next I indicate the code that is executed in the controller (where is what I previously told):
public function ordenform(Request $request)
{
$input = $request->all();
$request->validate([
'nombre' => 'required|string',
'apellido' => 'required|string',
'productos' => 'required',
'cantidades' => 'required|string',
'enviosino' => 'required|in:si,no',
]);
// Quantity Array
$cantidades = explode(',', $input['cantidades']);
if (count($cantidades) != count($input['productos'])) {
return back()->withErrors(['Las cantidades no corresponden a los productos agregados']);
}
$total = 0;
$ganancia = 0;
foreach ($input['productos'] as $producto) {
$producto = Product::find((int) $producto);
$total += $producto->value;
$ganancia += $producto->ganancia;
$producto->stock = (int) $producto->stock - 1;
$producto->save();
}
if ($input['enviosino'] == 'si') {
$total += (int) $input['envio'];
}
if ($input['envio'] == null) {
$input['envio'] = 0;
}
// Products IDS Array
$jsonproductos = json_encode($input['productos']);
Order::create([
'nombre' => $input['nombre'],
'apellido' => $input['apellido'],
'product_ids' => $finalprods,
'value' => $total,
'ganancia' => $ganancia,
'envio' => $input['envio'],
]);
$caja = Config::where('id', 1)->get()->first();
$caja->dinerototal += $total;
$caja->gananciatotal += $ganancia;
$caja->save();
return back()->with('success', 'Orden creada correctamente');
}
Finally, I need to pass as creation parameter the final array to the column products_ids (later I will modify the name).
Another option I thought of is passing objects to an array:
[{id: 1, quantity: 3}]
But I don't know how to get to create that object, I'm still kind of new hehe.
I hope I have explained myself well, English is not my native language. I'm sorry.
I am attentive to your comments !! Greetings.
PS: I am using Laravel
To achieve [{id: 1, quantity: 3}] there will be several idea, but it seems to be an arrayList, so below is how you can create an arrayList in PHP. I have not tested the code, just written here, but should give you the idea to achieve this.
I am considering one is Order class.
<?php
class Order {
private $id;
private $quantity;
public function setId(int $id) {
$this->id = $id;
return $this;
}
public function getId(){
return $this->id;
}
public function setQuantity(int $quantity) {
$this->quantity = $quantity;
return $this;
}
public function getQuantity(){
return $this-> quantity;
}
public function toArray(){
return [
'id' => $this->getId(),
'quantity' => $this->getQuantity()
];
}
}
?>
another is OrderList.
<?php
class OrderList {
private $orderList;
public function __construct(Order ...$orders) {
$this->orderList = $orders;
}
public function toArray(){
$arr = [];
foreach ($this->orderList as $order) {
$arr[] = $order->toArray();
}
return $arr;
}
}
?>
and then use like
$order1 = new Order();
$order1 = $order1->setId(1)->setQuantity(10);
$order2 = new Order();
$order2 = $order1->setId(2)->setQuantity(20);
$orderList = new OrderList($order1, $order2);
var_dump(json_encode($orderList->toArray()));
//Output
string(47) "[{"id":2,"quantity":20},{"id":2,"quantity":20}]"
You do not need json_encode, I have added it to print only.
Nevermind, resolved ->
$prodsfinal = array();
for ($i = 0; $i < sizeof($cantidades); $i++) {
$array = [
'id' => json_decode($input['productos'][$i]),
'cantidad' => (int) $cantidades[$i],
];
array_push($prodsfinal, $array);
}
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
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');
}
I have this problem in uploading my csv to my database (SQL). I am using Maatwebsite... And here's is my controller:
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['s_id' => $value->id,
'school_name' => $value->sname,
'region' => $value->reg,
'province' => $value->prov,
'municipality' => $value->mun,
'division' => $value->div,
'district' => $value->dis,
'enrollment_sy_2014_2015' => $value->enrolled,
'mooe_in_php_for_fy_2015' => $value->mooe,
'latitude' => $value->lat,
'longitude' => $value->lng
];
}
Map::insert($arr);
dd('Insert Record successfully.');
//return json_encode($arr);
}
}
dd('Request data does not have any files to import.');
}
Which gives me this endless error message:
The CSV contains only 200+ rows. Any help would be appreciated. Thanks in advance :))
Maybe try something like this, create new Model (assuming Map is the name of your Model and save():
<?php
class UploadCSV extends Controller
{
public function store(Request $request){
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$entry = new Map;
$entry->s_id = $value->id;
$entry->school_name = $value->sname;
$entry->region = $value->reg;
$entry->province = $value->prov;
$entry->municipality = $value->mun;
$entry->division = $value->div;
$entry->district = $value->dis;
$entry->enrollment_sy_2014_2015 = $value->enrolled;
$entry->mooe_in_php_for_fy_2015 = $value->mooe;
$entry->latitude = $value->lat;
$entry->longitude = $value->lng;
$entry->save();
}
}
}
dd('Request data does not have any files to import.');
}
}
I use some $query->andFilterWhere(...) to create my query.
and can see the final query by echo $query->createCommand()->rawSql;
when I copy the final query and past it on phpmyadmin, 2 record fetched but no result found in ActiveDataProvider.
Where is the point that I miss that?!
============================================
This is my code:
$query = Camera::find();
$post = Yii::$app->request->post();
$post2 = array_filter((array)$post);
if( count($post2) >0 ){
foreach($post2 as $k=>$v){
$query->andFilterWhere([ 'Like' , $k , $v ]);
}
}
if($post['State'] > 0){
$branches = Branch::find()->joinWith('city')->where('state_id='.((int)$post['State']))->all();
foreach( $branches as &$v){
$v = $v->brch_id;
}
$query->andFilterWhere([ 'IN' , 'brch_id' , $branches ]);
}
echo $query->createCommand()->rawSql;
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
The problem was this loop:
foreach( $branches as &$v){
$v = $v->brch_id;
}
I just replace it by:
$a = [];
foreach( $branches as $v){
$a[] = (int)$v->brch_id;
}
and DONE, Solved!!!!! :|
In your code you have
if( count($post2) >0 ){ // that means all fields filled
foreach($post2 as $k=>$v){
$query->andFilterWhere([ 'Like' , $k , $v ]);
}
}
And just after that you have a check for $post['State'] and you are using it for a joinWith. I Don't know what kinda search you are using (or what form did you build), but it seems you are searching for State in this both models... is that the correct behavior?
If that's correct, can you show us the raw sql query that worked for you, but not with ActiveDataProvider?
And can i ask why don't you use a class for this search and extends it from Camera?
It would be something similar to this:
public $state // fields that you Camera model don't have.
public function search($params){
$query = Camera::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere('like', 'attribute', $this->attribute);
// same for the others attributes here...
$query->joinWith(['nameOfRelationWithBranch' => function ($queryBranch) {
$queryBranch->joinWith(['city' => function ($queryCity) {
$queryCity->andFilterWhere('state_id', $this->state);
}]);
}]);
//echo $query->createCommand()->rawSql;
return $dataProvider;
}