Storing array of ids as different entity in Laravel -Mysql - laravel

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],
]);
}

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

How to add array values to another array

I have two sets of array A and B, array A and B on submission is supposed to enter a database table.
A(result)
array:2 [
0 => 7
1 => 8
]
B
array:3 [
"student_test_id" => 8
"question_id" => 4
"test_id" => 3
]
EXPECTED RESULT
On submit, i want the values of Array A and B to enter this table like this
id| student_test_id | test_id | question_id |result
1 | 8 | 3 | 4 | 7
2 | 8 | 3 | 4 | 8
WHAT I HAVE TRIED
$result = $request->result;
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
foreach($request->result as $result){
$test_log = new StudentTestLog();
$test_log->student_test_id = $array_conv["student_test_id"];
$test_log->question_id = $array_conv["question_id"];
$test_log->test_id = $array_conv["test_id"];
$test_log->result = $result['id'];
$test_log->save();
if($test_log->save()){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}
}
Please assist Thank you
When returning response from foreach except first all other iterations of loop are omitted as return ends method execution. You should move return statements outside the loop. Try something like this:
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
$data_to_persist = [];
foreach($request->result as $result){
array_push( $data_to_persist, [
'student_test_id' => $array_conv["student_test_id"],
'question_id' => $array_conv["question_id"],
'test_id' => $array_conv["test_id"],
'result' => $result['id']
]);
}
$saved = StudentTestLog::insert( $data_to_persist );
if($saved){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}

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

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'];

How to loop number and saved into table laravel

I have input and this input is will generate number sequentially like this
5.01
5.02
5.03
......
5.10
5.11
i get number 5 on first number is from my another data . u can see at my code .so how i can do this if this number start from '01' not '1' and if more than 10 this '0' in first number is deleted.
in my controller i saved in $data and looping this number from 01
So in my input controller is like that :
public function store(Request $request)
{
$data = $request['kode_induk'] + // i dont know what to do here for loop this input ,
$induk = IndukBelanja::create([
'user_id' => Auth::user()->id,
'kode_induk' => $request['kode_induk'],
'kode_rekening' => $data,
'uraian' => $request['uraian'],
'anggaran' => $request['anggaran'],
]);
if ($induk) {
return ['redirect' => route('rekening_induk')];
} else {
return response()->json([
'success' => false,
'message' => ' Gagal update!',
], 500);
}
}
how i can loop this number ? can someone help ?
Update its my database what i need
+----+------------+------------+------------+
| id |kode_induk |kode_rekening| uraian
+----+------------+------------+------------+
| 1 | 5 | 5.01 | some data
+----+------------+------------+------------+
| 2 | 5 | 5.02 | some data
+----+------------+------------+------------+
| 3 | 5 | 5.03 | some data
+----+------------+------------+------------+
| 4 | 5 | 5.04 | some data
+----+------------+------------+------------+
You can cast $data to int and then increment by 0.01 in a for loop.
$data = (int) $request['kode_induk'];
$numberOfSequencesToGenerate = 10;
for($i = 0; $i < $numberOfSequencesToGenerate; $++){
$induk = IndukBelanja::create([
'user_id' => Auth::user()->id,
'kode_induk' => $request['kode_induk'],
'kode_rekening' => $data + 0.01,
'uraian' => $request['uraian'],
'anggaran' => $request['anggaran'],
]);
}
The loop basically reads, run the the block of code while $i is less than $numberOfSequencesToGenerate. On each iteration increment $i by one.
I am assuming the DB field kode_rekening is of type double but if is not you can format it in PHP so is always has two decimal places with number_format(). Ex: number_format($data + 0.01, 2)

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