Laravel Many to Many sync with null - laravel

I'm trying to use sync function like that:
$round->competitors()->sync($fighters);
$fighter is :
Collection {#339 ▼
#items: array:3 [▼
0 => 5
1 => null
2 => 6
]
}
When it get to the null element, I get :
QueryException in Connection.php line 647:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'competitor_id' at row 1 (SQL: insert into `round_competitor` (`competitor_id`, `round_id`) values (, 29))
I get the same result if I try:
$round->competitors()->sync([null, null]);
But if I try:
$round->competitors()->attach(null);
it works without any problem???
Why is that happening???

Call filter() on your $fighters so that the null values are removed.
$round->competitors()->sync($fighters->filter());

If you do: $round->competitors()->attach(null); is it the same as if you just don't make any attach? That's probably why it is working!!

Related

Trying to get Values between 2 dates but need start date and end date should be as given instead of as per database

I am trying to get data between "Start" and "End" dates from database which is working fine and query giving me the result, Say
Start = 09-02-2022.
End = 10-03-2022.
Database values start = "01-03-2022 to 09-03-2022" so i am getting result from date say 16-02 to 01-03.
But i want result should start with 09-02 and end with 10-03. If value is not present in database then it should give as "0"
Check attached Image for reference.
Code for Getting dates for last 30 days -
$getalldates = array();
for($d = (Carbon::today()->subDays(30)); $d->lte(carbon::today()); $d->addDay())
{ $getalldates[] = $d->format('Y-m-d');}
Code for Getting data from database
$rahul = Buffalomilkrecord::select(DB::raw('date'), DB::raw('sum(totalmilk) as totalmilk, DATE_FORMAT(date,"%d") as "daykey"'))
->whereBetween('date', [$olddate, $todaydate] )
->groupBy(DB::raw('date'))
->orderBy('date','asc')
->get()->pluck('date')->toArray();
Thanks in Advance.
This is what i tried
$result = array();
foreach($getalldates as $date){
$totalmilk= Buffalomilkrecord::select(DB::raw('sum(totalmilk) as totalmilk'))->whereDate('date',$date)->pluck('totalmilk');
if($totalmilk){
$result[] = array($date =>$totalmilk);
} else {
$result[] = array($date =>0);
}
}
I am expecting
This is my output 0 => array:1 [▼ "2022-02-09" => Illuminate\Support\Collection {#348 ▼ #items: array:1 [▼ 0 => null ] }
and i am expecting "2022-02-09" = "0"
Check Image

Foreach only showing First item in array

I am trying to get data for each id using foreach. But when code run it get only data for 1 ID.. Following is the code
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->get('buffaloID')- >pluck('buffaloID')->toArray();
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dd([$buffalidforavgmilk,$milkperid]);
}
Output
array:2 [▼
0 => array:4 [▼
0 => "Buffalo-01"
1 => "Buffalo-02"
2 => "Buffalo-03"
3 => "Buffalo-04"
]
1 => array:5 [▼
0 => "Buffalo-01"
1 => "Buffalo-01"
2 => "Buffalo-01"
3 => "Buffalo-01"
4 => "Buffalo-01"
]
]
Here Loop giving only 1 ID where as required array for all 4 ID
( for Test, i try to get only buffaloID)
Thanks in Advance
dd interrupts execution. If you wanted to dump every result and then stop execution, you should have used dump instead
foreach ($buffalidforavgmilk as $id) {
$milkperid = Buffalomilkrecord::where('buffaloID', $id)->pluck('buffaloID')->toArray();
dump([$buffalidforavgmilk,$milkperid]);
}
dd('Done');
This is not ideal though. You are making a query in each iteration of the loop.
One way you could remove the foreach is to change your query to use whereIn.
$buffalidforavgmilk = Buffalodata::groupBy('buffaloID')->pluck('buffaloID')->toArray();
$milkperids = Buffalomilkrecord::whereIn('buffaloID', $buffalidforavgmilk)->pluck('buffaloID')->toArray();

how to save array data coming from view in laravel

This the data when user submit the form :
POST Data
_token
"JNDt8WC6kVbvrSdFTKSGnHsfzTuIsbthslf5Gqjs"
invoice_number
"15"
dateofbill
"2019-04-19"
customer_name
"praveen kumar tiwari"
customer_mobile
"8924001750"
sno
array:3 [▼
0 => "1"
1 => "2"
2 => "3"
]
item_name
array:3 [▼
0 => "jeans"
1 => "shirt"
2 => "lower"
]
qty
array:3 [▼
0 => "2"
1 => "3"
2 => "2"
]
price
array:3 [▼
0 => "20000"
1 => "232"
2 => "12"
]
gst
array:3 [▼
0 => "1200"
1 => "22"
2 => "12"
]
discount
array:3 [▼
0 => "100"
1 => "23"
2 => "12"
]
textarea
""
i cannot be able to store this data into a table. i am trying with for loop but getting an error "Undefined offset: 3".
Code inside the controller
for($i=0;$i<=count($request['sno']);$i++)
{
$invoice = new Invoice;
$invoice->sendbill_id=$bill->id;
$invoice->sno=$request['sno'][$i];
$invoice->item_name=$request->item_name[$i];
$invoice->qty=$request->qty[$i];
$invoice->price=$request->price[$i];
$invoice->gst=$request->gst[$i];
$invoice->discount=$request->discount[$i];
$invoice->save();
}
i want to store these 3 values comming in the array form (sno,item_name,qty,price,gst,discount) in 3 diffrent rows
You should try to use laravel eloquent to save it. Here is some example that you can check it out. Laravel : Many to many insertion
The problem you have is indeed your loop: for($i=0;$i<=count($request['sno']);$i++).
To be specific it is this right here <=:
$i<=count()
^^
Take a look at your array:
[
0 => "1"
1 => "2"
2 => "3"
]
You got a total of 3 objects. count($request['sno']) will therefore return 3 since the count() function does not start counting at 0!
However, calling an index (e.g. $request['sno'][1]) will not return the first object (0 => "1") but the second (1 => "2"). I think you see where I am going.
Since the loop will go on until $i equals 3 the loop will be completed 4 times. At the last time (where $i == 3) you try to get the 4th item out of your array which does not exist so an error message pops up: Undefined offset: 3.
To solve this just change this
$i<=count()
^^
to <. The loop will only be executed if $i is still smaller then 3. This is the case if $i == 2. No error message will pop up.
I do not want to attack or hurt you in any way, but it seems to me that you are relatively new to PHP. Of course, that's not a shame, but I'm wondering if a huge framework like Laravel is right for you. First the basics, then comes the advanced.
But that's only as a small comment and tip from me.

Laravel use MAX on join statement

I'm trying to find how can i use MAX on laravel QueryBuilder or Eloquent join statement, for example:
$userShoppings = \DB::table('shoppings')
->join('products', 'shoppings.product_id', '=', 'products.id')
->select('shoppings.*', 'products.name','products.amount','max(shoppings.ordering_count)')
->where('shoppings.user_ordering_ip', request()->ip())
->get();
in this code i want to get max ordering_count from shoppings table on select method, but i get this error:
Column not found: 1054 Unknown column 'max(shoppings.ordering_count)' in 'field list'
could any body help me to solve this problem?
UPDATE for paste wrong result
Collection {#449 ▼
#items: array:3 [▼
0 => {#446 ▼
+"id": 11
+"product_id": 25
+"user_ordering_ip": "127.0.0.1"
+"ordering_count": 3
+"created_at": "2017-12-25 09:41:01"
+"updated_at": "2017-12-25 09:41:01"
+"amount": "128,440"
+"max(shoppings.ordering_count)": 3
}
1 => {#445 ▼
+"id": 10
+"product_id": 26
+"user_ordering_ip": "127.0.0.1"
+"ordering_count": 1
+"created_at": "2017-12-25 09:32:13"
+"updated_at": "2017-12-25 09:32:13"
+"amount": "137,614"
+"max(shoppings.ordering_count)": 1
}
2 => {#452 ▼
+"id": 9
+"product_id": 49
+"user_ordering_ip": "127.0.0.1"
+"ordering_count": 2
+"created_at": "2017-12-24 17:59:29"
+"updated_at": "2017-12-24 18:35:25"
+"amount": "110,092"
+"max(shoppings.ordering_count)": 2
}
]
}
You could use DB::raw(). So:
$userShoppings = \DB::table('shoppings')
->join('products', 'shoppings.product_id', '=', 'products.id')
->select('shoppings.*', 'products.name','products.amount', DB::raw('max(shoppings.ordering_count)'))
->where('shoppings.user_ordering_ip', request()->ip())
// note: you'll need to also group by all the columns
// you're select in `shoppings.*`
->groupBy('products.name', 'products.amount', 'shoppings.id')
->get();
https://laravel.com/docs/5.5/queries#raw-expressions
For the groupBy() issue you're experiencing, it's possible that you have strict mode enabled for MySQL. You can disable it entirely in your database.php file by setting strict => false under your MySQL connection. However, this will disable all strict checks
If you want to simply disable ONLY_FULL_GROUP_BY, you can add a modes key to your mysql connection in database.php as follows:
modes' => [
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
]
This will explicitly enable the other checks, but omits ONLY_FULL_GROUP_BY

Laravel 5.4 whereNotIn apparently not working

I have logic in a controller that builds an array called $exclude.
Using dd for $exclude I get :
array:4 [▼
0 => 2
1 => 3
2 => 4
3 => 5
]
which is correct.
I want to exclude those from a result so I have:
$potype = DB::table('potypes')
->whereNotIn('id',[$exclude])
->get();
but when I run the query those items are included with the exception of the first in the array. So I enabled the query log with
DB::enableQueryLog();
and ran
dd(DB::getQueryLog());
with the result of
array:1 [▼
0 => array:3 [▼
"query" => "select * from `potypes` where `id` not in (?)"
"bindings" => array:4 [▼
0 => 2
1 => 3
2 => 4
3 => 5
]
"time" => 0.67
]
]
The table has 8 records but running the query is returning 7, only ommiting the first of the list:
Collection {#621 ▼
#items: array:7 [▼
If I use implode
$ex = implode(',',$exclude)
and change the query to
->whereNotIn('id',[$ex])
I get the same result - 7 items with just the first in the list being ignored.
Is this an Eloquent bug or me?
delete [ ] and check it again:
$potype = DB::table('potypes')
->whereNotIn('id',$exclude)
->get();
OK it was realtively simple with Mohammed's comment pointing me in the right direction.
As $exclude was an array I changed the get to:
$potype = DB::table('potypes')
->whereNotIn('id',$exclude)
->get();
and it worked OK!

Resources