How to sort two array value from lowest to highest and store in database - laravel

This is my array data from
$users = [1, 2, 3, 4];
$bidder = [3, 6, 7, 2];
And i want to sort like this
users_id | bidder
---------- ** ----------
4 | 2
1 | 3
2 | 6
3 | 7
and In Controller,using Collections I sort in this way
$users=$request->user_id;
$bidder=$request->bidder_rate;
$data = collect($users)->map(function ($user, $key) use ($bidder) {
return [
'user_id' => $user,
'bidder' => $bidder[$key]
];
})->sortBy('bidder');
Now when i do dd($data).It worked
1 => array:2 [▼
"user_id" => "2"
"bidder" => "10"
]
0 => array:2 [▼
"user_id" => "1"
"bidder" => "12"
]
2 => array:2 [▼
"user_id" => "4"
"bidder" => "15"
]
But now i want to save all user_id and bidder sorted data in respective field(user_id & bidder) in
array form.So how can i store them
$auction=new Auction();
$auction->name=$data['auction_name'];
$auction->user_id=$data['user_id']; //I think i cannot do like this
$auction->bidder=$data['bidder'];

Try this
$auction=new Auction();
$auction->name=collect($data)->pluck("user_id");
$auction->user_id=collect($data)->pluck("bidder");
$auction->bidder=$data['bidder'];

Related

How to bulk update table in Laravel?

I have a database table with the following columns:
columnindex | type | id
1 1 1
2 2 1
3 3 1
I have a input array:
$arr = [1 => 2, 2 => 5, 3 => 6,...]
As result I need this:
columnindex | type | id
1 2 1
2 5 1
3 6 1
How to use update bulk in this case?
I tried this but it is not optimized:
$arr = [1 => 2, 2 => 5, 3 => 6];
foreach($arr as $columnindex => $type) {
SessionPrepared::where("id", 1)->where("columnindex", $columnindex)->update(["type" => $type]);
}
You are looking for the upsert method (https://laravel.com/docs/9.x/eloquent#upserts).
Example:
SessionPrepared::upsert([
['id' => 1, 'columnindex' => 1, 'type' => 'value'],
['id' => 2, 'columnindex' => 2, 'type' => 'value'],
['id' => 3, 'columnindex' => 3, 'type' => 'value'],
], ['id', 'columnindex'], ['type']);
Results in it bulk updating the column type for the provider identifiers id & columnindex

Storing array of ids as different entity in Laravel -Mysql

I have A Table
id Primary bigint(20)UNSIGNED AUTO_INCREMENT,
school_id bigint(20)UNSIGNED Foreign Key,
teacher_id bigint(20)UNSIGNED Foreign Key,
course_id bigint(20)UNSIGNED Foreign Key,
klass_id bigint(20)UNSIGNED Foreign Key,
I Want to add Some data To this table, My data is given below.
{
"school_id":5,
"teacher_id":2,
"course_id":[1,2,3],
"klass_id":[7,8,3],
}
How Can I store this data Like Below
--id|school_id|teacher_id|course_id|klass_id
----------------------------------------------
1 | 5 | 2 | 1 | 7
2 | 5 | 2 | 2 | 8
3 | 5 | 2 | 3 | 3
If the input is always gonna be in the format of
"school_id" will have 1 value,
"teacher_id" will have 1 value,
"course_id" will have x values,
"klass_id" will have x values,
Then you can do something like:
$mapped = [];
for($i=0; $i<count($data['course_id']); $i++) {
$mapped[] = [
"school_id" => $data['school_id'],
"teacher_id" => $data['teacher_id'],
"course_id" => $data['course_id'][$i],
"klass_id" => $data['klass_id'][$i]
]
}
Then you can call any eloquent or DB function to insert like:
Model::insertMany($mapped);
P.S: There must be a better way of doing it that I don't know of. :(
Are you trying to save this data manually? if yes, create database SEED and add these data in array format like below: create a class with command php artisan make:seeder CreateSeedTableName and add this below code
$arr = [
[
"school_id" => 5,
"teacher_id" => 2,
"course_id" => 1,
"klass_id" => 7
],
[
"school_id" => 5,
"teacher_id" => 2,
"course_id" => 2,
"klass_id" => 8
],
[
"school_id" => 5,
"teacher_id" => 2,
"course_id" => 3,
"klass_id" => 3
]
];
TableName::insert($arr);
or you can use loop if you have same format data in request.
$count = count($data['course_id']); //get course count
$schoolId = $data['school_id']; //get school id
$teacherId = $data['teacher_id']; //get teacher id
for ($i = 0; $i < $count; $i++) {
TableName::create([
'school_id' => $schoolId,
"teacher_id" => $teacherId,
"course_id" => $data['course_id'][$i],
"klass_id" => $data['klass_id'][$i],
]);
}

Laravel 5.8 - collect method return me undefined index

I got this array:
What I want to do next is to make a collection from the array and I write:
$variant_images = collect($p->images);
but I got the error:
"Undefined index: images"
What's bad in my code and how to solve it?
Assuming $p is array like this
$p = [
'images' => [
1, 2, 3, 4
]
];
you can write
$collection = collect($p);
// access the images
var_dump($collection->get('images'));
and the output would be
array:4 [▼
0 => 1
1 => 2
2 => 3
3 => 4
]

Adding missing rows of data in a collection - unexplanable Laravel behavior

I have a table of data and I need to fetch an array from it, that looks like this:
[
['Mon', 25],
['Tue', 13],
['Thu', 25]
]
I'm achieving this through some collection acrobatics. At some point I am mapping the collection adding the numerical value of that day (1 Monday, 2 Tuesday) as a key, so I can sortKeys() later.
The problem is not all days are always present and I want to add them with a value of 0 at their respective place.
My first attempt was foreach on an array of days of the week, and if
$collection->flatten()->search($day) returns false, prepend that day. This works fine, but Thu always get appended. It never returns true on the search even though it's copied and pasted and should be identical. All other days are skipped/prepended correctly...
Then I tried array_search on toArray() and the same thing happened. Thu never returns true ...
This is extremely weird, basically Thu == Thu returns false
Is there anyway I can use array_merge or something like that to make it better (or get it working at all?).
This is one way of doing it. It could be done much cleaner, if your data was structured different in the first place, like using day name/value as key, instead of having both in sub arrays, but I will keep to the original question:
$defaultDays = collect([
['Mon', 0],
['Tue', 0],
['Wed', 0],
['Thu', 0],
['Fri', 0],
['Sat', 0],
['Sun', 0],
]);
$days = [
['Mon', 25],
['Tue', 13],
['Thu', 25]
];
// Use $defaultDays to map, as we will need all seven days no matter what.
$days = $defaultDays->map(static function (array $defaultDay) use ($days) {
// Current match is the default day...
$match = $defaultDay;
foreach ($days as $day) {
if ($day[0] === $defaultDay[0]) {
$match = $day;
}
}
return $match;
});
This will result in:
Illuminate\Support\Collection {#1388
#items: array:7 [
0 => array:2 [
0 => "Mon"
1 => 25
]
1 => array:2 [
0 => "Tue"
1 => 13
]
2 => array:2 [
0 => "Wed"
1 => 0
]
3 => array:2 [
0 => "Thu"
1 => 25
]
4 => array:2 [
0 => "Fri"
1 => 0
]
5 => array:2 [
0 => "Sat"
1 => 0
]
6 => array:2 [
0 => "Sun"
1 => 0
]
]
}

laravel Maatwebsite validate sum multi column

hi im using Maatwebsite with laravel everything working so good so far ..
but i want to update excel like this ..
number date amount
1 2020-01-01 10
1 2020-01-01 -5
1 2020-01-01 -5
2 2020-02-02 20
2 2020-02-02 -20
3 2020-03-03 50
3 2020-03-03 -50
3 2020-03-03 40
3 2020-03-03 -40
what i want thats the sum of the amount with number 1 sould return 0 or end the import
number date amount
1 2020-01-01 10
1 2020-01-01 -5
1 2020-01-01 -5
how can i check this (10 + -5 + -5 == 0) or fail
and for 2 and 3 ect ..
thanks a lot
I explained all the steps in comments but I will explain here as well.
When you loop through each row, you first need to grab all the rows where number field is 1, 2 or 3, what ever the number is currently in the iteration.
In this case, the first loop results will be:
number date amount
1 2020-01-01 10
1 2020-01-01 -5
1 2020-01-01 -5
Then you sum (add up) the values from the amount column.
In this case, it will sum like this:
10
-5
-5
-----
0
If the answer is not 0, take the current sheet ($sheet) and return what you currently have, to be exported.
Full class:
...
use Maatwebsite\Excel\Concerns\FromArray;
class ExampleExport implements FromArray
{
public function array() : array
{
// EXAMPLE hardcoded data for the purpose of this demo
$rows = [
[
'number' => 1,
'date' => '2020-01-01',
'amount' => 10
],
[
'number' => 1,
'date' => '2020-01-01',
'amount' => -5
],
[
'number' => 1,
'date' => '2020-01-01',
'amount' => -5
],
[
'number' => 2,
'date' => '2020-02-02',
'amount' => 20
],
[
'number' => 2,
'date' => '2020-02-02',
'amount' => -20 // <-------- Change this to -21 to test
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => 50
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => -50
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => 40
],
[
'number' => 3,
'date' => '2020-03-03',
'amount' => -40
],
];
// EXAMPLE hardcoded data for the purpose of this demo
$rows = collect($rows);
// You probably going to get this from your database so should look like this:
// $rows = \App\Model::all(['number', 'date', 'amount']); // OR below
// $rows = DB::table('examples')->select(['number', 'date', 'amount'])->get();
// Blank sheet
$sheet = [];
foreach ($rows as $row) {
// Get all the rows where the `number` field has the same value,
// for example 1, 2, or 3, then sum the `amount` field (add up).
//
// If the amount does not add up to 0, stop and return what you currently got
if ($rows->where('number', $row['number'])->sum('amount') !== 0) {
return $sheet;
}
// Else, add them to the sheet and continue.
$sheet[] = $row;
}
return $sheet;
}
}
Results:
When amount adds up to 0:
When amount does not add up to 0:

Resources