Let's say I've got eloquent collection returns from:
$b = Book::get(); (columns: id, book_name, pages)
$m = Magazine::get(); (columns, id, mag_name, type)
How do I then:
Combine them in the same collection.
Rename ->book_name/mag_name to k
Add type and if book use 'null' as value
add ->hash (str::random)
I want to keep the collection to be able to use the benifits that come with it. ie. not convert it to an array.
Laravel 7
You can do it with collection merge method
$b = Book::get(['id','book_name as k','pages']);
$m = Magazine::get(['id','mag_name as k','type']);
$bb = $b->map(function ($book){
$book['type'] = null;
$book['hash'] = Str::random();
return $book;
});
$mm = $m->map(function ($magzine){
$magzine['hash'] = Str::random();
return $magzine;
});
$merged = $bb->merge($mm);
return $merged;
Assume we have the following collections:
$b = Book::get(); //(columns: id, book_name, pages)
$m = Magazine::get(); //(columns, id, mag_name, type)
Second, update the fields:
$books = $b->map(function ($book) => {
return [
'id' => $book->id,
'k' => $book->book_name,
'type' => null,
'hash' => Str::random()
];
});
$magazines = $b->map(function ($magazine) => {
return [
'id' => $magazine->id,
'k' => $magazine->mag_name,
'type' => $magazine->type,
'hash' => Str::random()
];
});
Third, merge the collections:
$result = $books->merge(magazines);
Related
I have a small response from db model, and i colud rebase it and response in route, but i see error.
My Controller:
class PostController extends Controller {
public function getLastRecord() {
$lastRec = Post::latest('created_at')->first();
$res = [];
$res = collect($lastRec)->map(function($record) {
return [
'id' => $record->post_id,
'rec_name' => $record->post_name,
'user' => $record->user_id,
];
})->toArray();
return $res;
}
}
I want that response will be array
['id': 1, 'rec_name': 'test_name', 'user': 1]
instead names from db
['post_id': 1, 'post_name': 'test_name', 'user_id': 1]
Error:
Attempt to read property "post_id" on int
When you collect() a single Record, then call ->map() (or other iterative methods), it loops over your Model's columns, not multiple Post records. You can solve this by wrapping $lastRec in an array, or using ->get() instead of ->first():
$lastRec = Post::latest('created_at')->first();
return collect([$lastRec])->map(function($record) {
return [
'id' => $record->post_id,
'rec_name' => $record->post_name,
'user' => $record->user_id,
];
})->toArray();
// OR
$lastRecs = Post::latest('created_at')->get();
return $lastRecs->map(function ($record) {
return [
'id' => $record->post_id,
'rec_name' => $record->post_name,
'user' => $record->user_id,
];
})->toArray();
Or, since this is a single record (using ->first() only ever returns 1 record), you don't need to collect() or map() at all:
$lastRec = Post::latest('created_at')->first();
return [
'id' => $lastRec->post_id,
'rec_name' => $lastRec->post_name,
'user' => $lastRec->user_id
];
I am getting a issue while fetching array data in Laravel 7 here is my code
https://i.stack.imgur.com/IZbg6.png
and the result is : https://i.stack.imgur.com/ByKaV.png
It is fetching only one array data. I don't know where i am missing.
If anybody know the error, please help me to solve this issue.
Below is my code ======================================
$cat_id = $category->id;
$location = null;
$sites = \DB::select( 'SELECT id FROM sites WHERE category_id = ?', [ $category->id ]);
$all = [ ];
foreach( $sites as $s ) {
$all[ ] = $s->id;
}
$sites = $all;
$all_cat_id = implode(',', array_map('intval', $sites));
// echo "<pre>";
// print($all_cat_id);
// die();
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->where('id', [$all_cat_id])->paginate(10);
return view('browse-category', [ 'activeNav' => 'home',
'reviews' => $reviews,
'sites' => $sites,
'category' => $category,
'all_categories' => $all_categories,
'location' => $location
]);
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->whereIn('id', [$all_cat_id])->paginate(10);
You need to use whereIn() instead of where()
whereIn() checks column against array.
I am storing records for my product transfer app using 3 tables in single action. Transferhistories, Warehouse1StockSummaries and Warehouse2StockSummaries.
storing records to trasnferinghistories is ok, and also the increment method I declare to Warehouse2StockSummaries is also working fine except for Warehouse1StockSummaries.
here's my store function,
public function store(Request $request)
{
$input = $request->all();
$items = [];
for($i=0; $i<= count($input['product_id']); $i++) {
// if(empty($input['stock_in_qty'][$i]) || !is_numeric($input['stock_in_qty'][$i])) continue;
if(!isset($input['qty_in'][$i]) || !is_numeric($input['qty_in'][$i])) continue;
$acceptItem = [
'product_id' => $input['product_id'][$i],
'transfer_qty' => $input['qty_out'][$i],
'user_id' => $input['user_id'][$i]
];
array_push($items, Transferhistories::create($acceptItem));
// dd($input);
//update warehouse 1 summary
$warehouse1summary = Warehouse1StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if (!$warehouse1summary->wasRecentlyCreated) {
$warehouse1summary->increment('qty_out', $input['qty_out'][$i]);
}
//update warehouse 2 summary
$stock2Summary = Warehouse2StockSummaries::firstOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_out'][$i],'qty_out' => null]);
if (!$stock2Summary->wasRecentlyCreated) {
$stock2Summary->increment('qty_in', $input['qty_in'][$i]);
}
}
return redirect()->route('transferHistory.index');
}
updating warehouse 1 summary is not doing what it should be.
any suggestion master? thank you so much in advance!
According to laravel, firstOrCreate does not save the value, so after you do:
$warehouse1summary = Warehouse1StockSummaries::updateOrCreate(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
Edit
The method firstOrNew will return the first or a instance of the Model.
So what you wanna do is this:
$warehouse1summary = Warehouse1StockSummaries::firstOrNew(
['product_id' => $input['product_id'][$i]],
['qty_in' => $input['qty_in'][$i],
'qty_out' => $input['qty_out'][$i]
]);
if(isset($warehouse1summary->created_at)){
$warehouse1summary->qty_out = $warehouse1summary->qty_out + $input['qty_out'][$i];
}
$warehouse1summary->save();
This should be like this
ID|access1|access2|access3|
and values:
1|1|0|1
//myController
$basic_data = array();
$select_access1 = $_POST("select_access1");
$select_access2 = $_POST("select_access2");
$select_access3 = $_POST("select_access3");
$select_access4 = $_POST("select_access4");
$select_access5 = $_POST("select_access5");
$basic_data[] = array('accs_trans_sec'=>$select_access1,'accs_acctng_sec'=>$select_access2, 'accs_admin_sec'=>$select_access3,'accs_dashboard_sec'=> $select_access4, 'accs_reports_sec'=>$select_access5);
$this->RoleModel->saveRole($basic_data);
//myModel
public function saveRole($basic_data)
{
foreach($basic_data as $value) {
$this->db->insert('roles_global_access', $basic_data);
}}
You can set that data to array just like this:
$data = array(
'column1' => 'My Value 1',
'column2' => 'My Value 2',
'column3' => 'My Value 3'
);
$this->db->insert("table_name", $data);
Let's assume that you are getting the values of your checkbox based on your $_POST variables.
Since you've declared $basic_data as array() no need to cast it as $basic_data[].
So on your controller it should be like this:
$basic_data = array(
'accs_trans_sec'=>$select_access1,
'accs_acctng_sec'=>$select_access2,
'accs_admin_sec'=>$select_access3,
'accs_dashboard_sec'=> $select_access4,
'accs_reports_sec'=>$select_access5
);
And your model there's no need to use loop since you are inserting Object data it should look like this:
public function saveRole($basic_data)
{
$this->db->insert('roles_global_access', $basic_data);
return ($this->db->affected_rows() != 1) ? false : true;
}
so basically, if the model returns true then it successfully inserted the data.
To check if data is inserted successfully:
$result = $this->RoleModel->saveRole($basic_data);
if($result == true){
echo ("Successfully inserted!");
}else{
echo ("Problem!");
}
First, you are not getting post data in the correct way. With $_POST have to use square brackets [].
Second, Don't use foreach loop in the model
Get data in the controller like this
$basic_data = array(
'accs_trans_sec' => $_POST['select_access1'],
'accs_acctng_sec' => $_POST['select_access2'],
'accs_admin_sec' => $_POST['select_access3'],
'accs_dashboard_sec' => $_POST['select_access4'],
'accs_reports_sec' => $_POST['select_access5']
);
$this->RoleModel->saveRole($basic_data);
Model
public function saveRole($basic_data){
return $this->db->insert('roles_global_access', $basic_data);
}
You should try this.
Controller:
$this->RoleModel->saveRole($_POST);
Model:
public function saveRole($basic_data){
extract($basic_data);
$dataset = array(
'accs_trans_sec' => $basic_data['select_access1'],
'accs_acctng_sec' => $basic_data['select_access2'],
'accs_admin_sec' => $basic_data['select_access3'],
'accs_dashboard_sec' => $basic_data['select_access4'],
'accs_reports_sec' => $basic_data['select_access5']
);
$this->db->insert('roles_global_access', $dataset);
}
I have a sql request concerning admin :
$admin = Admin::findOrFail(Auth::guard('admin')->user()->id);
from this sql request I also manage to get the users of the admin ...
$users = $admin->users;
Each users must follow training sessions. and I must calculate it by using SQL requests for each users ... So i wrote this foreach statement
foreach ($users as $user) {
$todo = User::select() .....where('users.id' = $user->id)->get();
$done = User::select() .....where('users.id' = $user->id)->get();
$totalTimes = $todo->toBase()->sum('dureeformation');
$spendTimes = $done->toBase()->sum('dureeformation');
$remainingTimes = $totalTimes - $spendTimes;
$timeData[] = ['id' => $user->id, 'totalTime' => $totalTimes, 'spendTime' => $spendTimes, 'remainingTime' => $remainingTimes];
}
the totalTimes, spendTimes and remainingTimes are operations on Collections and i get expected results ...
$users->each(function ($record) use ($timeData) {
$record['totalTime'] = $timeData[$record['id']]['totalTime'];
$record['spendTime'] = $timeData[$record['id']]['spendTime'];
$record['remainingTime'] = $timeData[$record['id']]['remainingTime'];
//dd($record['totalTime']);
});
After this :
$timeData = collect($timeData);
$timeData= $timeData->keyBy('id');
$users = collect($users->toArray());
I have an issue here :
$users->each(function ($record) use ($timeData) {
$record['totalTime'] = $timeData[$record['id']]['totalTime'];
$record['spendTime'] = $timeData[$record['id']]['spendTime'];
$record['remainingTime'] = $timeData[$record['id']]['remainingTime'];
//var_dump($record);
});
$record in the function gives me what i expect ... the var_dump($records) added columns where it was expected but i can't take those results out of the function.
I tried to do this :
$variable = $users->each(function ($record) use ($timeData)...
dd($variable)
but unsuccessfully ...
Looks to me like your $timeData array is built differently than you access it. In your code you are doing
$timeData[] = [
'id' => $user->id,
'totalTime' => $totalTimes,
'spendTime' => $spendTimes,
'remainingTime' => $remainingTimes,
];
which will produce an array like this
[
0 => [
'id' => 17,
'totalTime' => 5,
'spendTime' => 4,
'remainingTime' => 3
],
1 => [
'id' => 17,
'totalTime' => 7,
'spendTime' => 5,
'remainingTime' => 2
]
]
but what you actually want is to have the id as index, right? Then you'd have to build the array this way:
$timeData[$user->id] = [
'totalTime' => $totalTimes,
'spendTime' => $spendTimes,
'remainingTime' => $remainingTimes,
];
or, as an alternative, perform a different lookup:
$users->each(function ($record) use ($timeData) {
$times = array_first($timeData, function ($value, $key) use ($record) {
return $value['id'] === $record['id'];
});
$record['totalTime'] = $times['totalTime'];
$record['spendTime'] = $times['spendTime'];
$record['remainingTime'] = $times['remainingTime'];
});
Both solutions have pros and cons, though. On the one hand, using the user identifier as the index will produce a huge array that is only filled partially. On the other hand, the second solution is a bit slower. As long as you are not going to deal with thousands of entries in the $timeData array, this won't be an issue, though.