For example i have "id, name, wage, sex, age" columns.
1, John, 3, M, 30
2, Angela, 5, F, 26
If i have 50 rows like this. And if i want to save name, wage into table1 & sex and age into table2. In laravel docs queries/insert, they told us make an array and put values on it. But how should i put some of the values into table1 and other values into table2 in same foreach.
foreach($test as $tests)
{
$data[] =[
'name' => $tests->name,
'wage' => $tests->wage,
'sex' => $tests->sex,
'age' => $tests->age
];
}
Products::insert($data);
Is this the right ways to do it? I cant figure out the correct way to do.
If these tables are not related, you can do it with just 2 queries:
foreach ($tests as $test) {
$products[] = [
'name' => $tests->name,
'wage' => $tests->wage
];
$otherData[] = [
'sex' => $tests->sex,
'age' => $tests->age
];
}
Products::insert($products);
OtherModel::insert($otherData);
In case if these models are related, you'll need to create 51 query instead of 2 (still better than 100 queries):
foreach ($tests as $test) {
$productId = Products::insertGetId([
'name' => $tests->name,
'wage' => $tests->wage,
]);
$otherData[] = [
'sex' => $tests->sex,
'age' => $tests->age,
'product_id' => $productId
];
}
OtherModel::insert($otherData);
If these models are related and you still want to do this with just a few queries, you could use transactions:
DB::transaction(function () {
$productId = (int)DB::table('products')->orderBy('id', 'desc')->value('id');
foreach ($tests as $test) {
$productId++;
$products[] = [
'name' => $tests->name,
'wage' => $tests->wage
];
$otherData[] = [
'sex' => $tests->sex,
'age' => $tests->age,
'product_id' => $productId
];
}
Products::insert($products);
OtherModel::insert($otherData);
});
you could loop trough data and insert into DB table.
foreach($test as $tests)
{
$product = new Products();
$product->name = $tests->name;
$product->name = $tests->name;
$product->save();
$another = new AnotherTableModel();
$another->sex= $tests->sex;
$another->age= $tests->age;
$another->save();
}
Related
this my code cause the trouble,
$cust = Customer::where('name', '=', $data[$i][0]['customer_name'])
->pluck('customer_id')[0];
this one for get customer id when i do store to sales order
$sales = array(
'customer_id' => Customer::where('name', '=', $data[$i][0]['customer_name'])->pluck('customer_id')[0],
'logistics_id' => Logistic::where('logistics_name', '=', $data[$i][0]['logistics'])->pluck('logistics_id')[0],
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp']
);
$store_so = SalesOrder::create($sales);
but, when i do dd(), i get the right data
First of all, you need to check if the $data variable returns the data as you expect.
dd($data);
Next, you need to check that the $data array has the number of elements according to $total_data.
dd(count($data) == $total_data));
So basically, you just need to give condition or try-catch (recommended) :
if (isset($data[$i][0])) {
$customer = Customer::where('name', $data[$i][0]['customer_name'])->first();
$logistic = Logistic::where('logistics_name', $data[$i][0]['logistics'])->first();
if(!$customer){
dd('No customer found!');
}
if(!$logistic){
dd('No logistic found!');
}
$sales = [
'customer_id' => $customer->customer_id,
'logistics_id' => $logistic->logistics_id,
'subtotal' => $data[$i][0]['subtotal_rp'],
'shipping_cost' => $data[$i][0]['shipping_cost_rp'],
'discount_code' => 0,
'date_of_sales' => $data[$i][0]['date'],
'grand_total' => $data[$i][0]['grand_total_rp'],
'tax' => $data[$i][0]['tax_rp'],
'status' => $data[$i][0]['status'],
'discount_amount' => $data[$i][0]['discount_amount_rp'],
];
$store_so = SalesOrder::create($sales);
}
else{
dd('No $data[$i][0] found!');
}
PS : I recommend using the first() method instead of pluck('customer_id')[0].
It seems you need to get a customer_id from a customer_name.
Try to make everything simple:
$sales = array(
'customer_id' => Customer::where('name', $data[$i][0]['customer_name'])->first()->id,
...
);
How would one do the following elegantly with laravel collections ?
Map the values of the $baseMap as keys to the collection.
The baseMap :
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
The collection :
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
//...
]);
The end result :
$result =[
[
'new_name' => 'name1',
'new_year' => '1000',
],
[
'new_name'=> 'name2',
'new_year' => '2000',
],
];
I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).
$result = $items->map(function($item) use ($baseMap) {
$array = [];
foreach($baseMap as $oldKey => $newKey){
if(isset($item[$oldKey])){
$array[$newKey] = $item[$oldKey];
}
}
return $array;
});
$result = $result->toArray();
Thanks to #vivek_23 and #IndianCoding for giving me idea's I ended up with the following :
I made a small edit to make sure the mapping and the items keys lined up.
so you don't have to worry of misalignment and all in laravel collection !
$baseMap = collect($baseMap)->sortKeys();
$result = $items->map(function ($item) use ($baseMap) {
return $baseMap->values()
->combine(
collect($item)->sortKeys()->intersectByKeys($baseMap)
)
->all();
});
Use intersectByKeys to filter your baseMap keys with $items values.
$result = $items->map(function($item,$key) use ($baseMap){
return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});
dd($result);
Update:
In a pure collection way,
$baseMapCollect = collect($baseMap);
$result = $items->map(function($item,$key) use ($baseMapCollect){
return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});
dd($result);
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
])->map(function($item, $key) use ($baseMap) {
return [
$baseMap['name'] => $item['name'],
$baseMap['year'] => $item['year']
];
});
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();
I have 3 tables (2 + pivot) :
categories
id
admin_id
created_at
updated_at
deleted_at
langs
id
langname_fr
langname
....
lang_sector
lang_id
sector_id
sectname
sectshortname
....
I created a form which allow to create several entries depending the number of languages i defined ...
{!! Form::open( array('route' => 'maps.store','method' => 'POST') ) !!}
<fieldset>
<legend>Nom du secteur</legend>
#foreach($langs as $lang)
<div class="form-group m-form__group">
{{ Form::label( 'Nom du secteur en ' . $lang->langname_fr) }}
{{ Form::text('sectname_lang_' . $lang->id, '' , [ 'class' => 'form-control m-input' ]) }}
</div>
<div class="form-group m-form__group">
{{ Form::label( 'Nom abrégé du secteur en ' . $lang->langname_fr ) }}
{{ Form::text('sectshortname_lang_' . $lang->id, '', [ 'class' => 'form-control m-input' ]) }}
</div>
#endforeach
</fieldset>
...
{!! Form::close() !!}
If i want to create an entry in my database, i have to create several entries ...
public function sectorCreate(Request $request) {
Sector::create(array(
'admin_id' => Auth::guard('admin')->user()->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
));
$sector = Sector::all()->last();
$sector_id = Sector::all()->last()->id;
$countLang = Lang::count();
for ($i = 1; $i <= $countLang; $i++) {
$insertSector[$i] = $sector->langs()->attach(
$sector_id,
[
'lang_id' => $i,
'sectname' => $request->input('sectname_lang_' .$i),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$i)),
'sectshortname' => $request->input('sectshortname_lang_' .$i),
'sectdescription' => $request->input('sectdescription_lang_' .$i),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$i),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
}
return redirect()->route('admin.home')->with('success', 'Secteur créé');
}
Now my issue is to know how i can update the values of the database and to delete the entry ... I tried to read the documentation but i'm not sure i understood it.
For example
lang_id sector_id sectname sectshortname
-------------------------------------------------------
1 1 longname1 shortname1
2 1 longname2 shortname2
After update i would like to update sectname and sectshortname ... I have made several trials using sync, syncWithoutDetaching and updateExistingPivot without success...
I also add constraints by considering lang_id and sector_id as a primary key ...
UPDATE ----------------------------------------------------------
I modified the update method using sync and syncWithoutDetaching
public function update(Request $request, $id)
{
$sector = Sector::findOrFail($id);
$countLang = Lang::count();
$langs = Lang::all();
foreach ($langs as $lang) {
$lang_id = $lang->id;
}
for ($i = 1; $i <= $countLang; $i++) {
$insertSector[$i] = $sector->langs()->sync(
$sector->id,
$lang_id,
[
'sectname' => $request->input('sectname_lang_' .$i),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$i)),
'sectshortname' => $request->input('sectshortname_lang_' .$i),
'sectdescription' => $request->input('sectdescription_lang_' .$i),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$i),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
}
return $insertSector;
//return redirect()->route('maps.index')->with('success', 'updated');
}
The Documentation states the following:
When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:
$user->roles()->attach($roleId, ['expires' => $expires]);
You got this part correct. Now for updating (and or deleting):
Deleting
$user->roles()->detach([1, 2, 3]);
This removes associated records and clears the intermediate table.
Syncing Associations
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:
$user->roles()->sync([1, 2, 3]);
You may also pass additional intermediate table values with the IDs:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
If you do not want to detach existing IDs, you may use the syncWithoutDetaching method:
$user->roles()->syncWithoutDetaching([1, 2, 3]);
Conclusion
Use sync, and set the attributes again. If you just want to update a few records, use the syncWithoutDetaching.
Update
Change your update code to this:
$insertSector[$i] = $sector->langs()->sync(
$lang_id =>
[
'sectname' => $request->input('sectname_lang_' .$i),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$i)),
'sectshortname' => $request->input('sectshortname_lang_' .$i),
'sectdescription' => $request->input('sectdescription_lang_' .$i),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$i),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
You passed both the sector->id and the $lang_id where you only needed to pass the $lang_id with attributes for the intermediate table.
Finally thanks to Douwe de Haan i finally solved my issue for creating an entry with pivot table ... i guess i understood a little bit how it work now
Here is the method :
public function store(Request $request)
{
Sector::create(array(
'admin_id' => Auth::guard('admin')->user()->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
));
$sector = Sector::all()->last();
$countLang = Lang::count();
$langs = Lang::all();
foreach ($langs as $lang) {
$lang_id[] = $lang->id;
}
for ($i=0 ; $i < $countLang; $i++) {
$insertSector[$i] = $sector->langs()->syncWithoutDetaching(
[$lang_id[$i] =>
[
'sectname' => $request->input('sectname_lang_' .$lang_id[$i]),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$lang_id[$i])),
'sectshortname' => $request->input('sectshortname_lang_' .$lang_id[$i]),
'sectdescription' => $request->input('sectdescription_lang_' .$lang_id[$i]),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$lang_id[$i]),
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
]
);
}
return redirect()->route('maps.index')->with('success', 'Secteur créé');
}
For updating :
public function update(Request $request, $id)
{
$sector = Sector::findOrFail($id);
$countLang = Lang::count();
$langs = Lang::all();
foreach ($langs as $lang) {
$lang_id[] = $lang->id;
}
for ($i=0 ; $i < $countLang; $i++) {
$insertSector[$i] = $sector->langs()->updateExistingPivot(
$lang_id[$i],
[
'sector_id' => $request->input('sector_id'),
'sectname' => $request->input('sectname_lang_' .$lang_id[$i]),
'sectname_slug' => Str::slug($request->input('sectname_lang_' .$lang_id[$i])),
'sectshortname' => $request->input('sectshortname_lang_' .$lang_id[$i]),
'sectdescription' => $request->input('sectdescription_lang_' .$lang_id[$i]),
'sectshortdescription' => $request->input('sectshortdescription_lang_' .$lang_id[$i]),
'updated_at' => Carbon::now(),
'deleted_at' => NULL
]
);
}
return $insertSector;
//return redirect()->route('sectors.index')->with('success', 'Secteur mis à jour');
}
I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;