Retrive Bulk Inserted ids after insert() function in Laravel 6+ - php

I Research a lot but Could not find any solution. So i am posting it Here
My problem is After Inserting bulk rows i want to get all the inserted ids to save the ids to another Pivot table.. Here is my code
$create_market = [];
$create_market_possibility = [];
foreach ($request->type0 as $key => $value) {
array_push($create_market, [
'market_id' => $value['market_id'],
'event_id' => $value['event_id'],
'name' => $value['name'],
'bet_min' => $value['min_bet'],
'bet_max' => $value['max_bet'],
'commission' => $value['commission'],
'type' => 0,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
}
foreach ($request->type1 as $key => $value1) {
array_push($create_market, [
'market_id' => $value1['market_id'],
'event_id' => $value1['event_id'],
'name' => $value1['name'],
'bet_min' => $value1['min_bet'],
'bet_max' => $value1['max_bet'],
'commission' => $value1['commission'],
'type' => 1,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
foreach ($value1['possibility'] as $key => $value2) {
array_push($create_market_possibility, [
// because i am not getting the inserted ids here i cant push it here
// that is the problem i am facing
'market_id' => $value1['market_id'],
'event_id' => $value1['event_id'],
'possibility' => $value2['possibility'],
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now()
]);
}
}
Market::insert($create_market);
// Here i want to retrive the last inserted all ids and put then in the obj of
[$create_market_possibility] array ...
if(count($create_market_possibility) > 0) {
MarketPossibility::insert($create_market_possibility);
}
$response = [
'status' => true,
'message' => 'Market Successfully Created'
];
return response()->json($response); //# sending response
i did this thing wher i was using create() for single insert
$id = Market::create($array)
It was returning me the object.. But in this case i have to insert multiple rows..
If there any other way to do it please let me know , Thank You!

1. For type0
You can run Market::insert($array) for type0 since there is no associated MarketPossibility
2. For type1,
You will have to create each Market one by one then associate it - you can use saveMany() to make it cleaner a faster:
$market = Market::create([...])
$new_market_possibility = [];
foreach ($value1['possibility'] as $key => $value2) {
$new_market_possibility[] = new App\MarketPossibility([...]);
}
$market->marketPossibilities()->saveMany($new_market_possibilities);
All that assuming that you have standard relations in place between Market and MarketPossibility

Related

How can i avoid update a password in Laravel when the password input field is left empty?

I got this code in laravel that allows an administrator to update an user's password:
public function editarmembro(Request $dados) {
$validatedData = $dados->validate([
'name' => 'required',
'email' => 'required',
'credencial' => 'required',
]);
$dados = $dados->all();
if (!empty($dados['password'])) {
$dados['password'] = Hash::make($dados['password']);
}
DB::table('users')->where('id', $dados['id'])->update(
[ 'name' => $dados['name'], 'email' => $dados['email'], 'credencial' => $dados['credencial'], 'password' => $dados['password'], 'sobre' => $dados['sobre'], 'updated_at' => Carbon::now(), ]
);
return redirect()->route('membros')->with('mensagemSucesso', 'As informações do membro "'.$dados['name'].'" foram atualizadas com sucesso.');
}
My problem is, if he left the password field blank, i get an error screen saying that the password field cannot be NULL. I want my code to NOT update the password if he left the password field blank, but DO update if he inserts something in password field.
Help, pls.
You can remove it from the $dados array if it's empty:
if (!empty($dados['password']))
$dados['password'] = Hash::make($dados['password']);
else
unset($dados['password']);
or with ternary operator
!empty($dados['password'])? $dados['password'] = Hash::make($dados['password']): unset($dados['password']);
and since all the names of the fields match those of the request and the updated_at field should auto-complete, you don't need to reassemble the array for the update.
DB::table('users')->where('id', $dados['id'])->update($dados);
If you want to reassemble the array anyway, you can do so
$update_dados = [
'name' => $dados['name'],
'email' => $dados['email'],
'credencial' => $dados['credencial'],
'sobre' => $dados['sobre'],
'updated_at' => Carbon::now(),
];
if (!empty($dados['password']))
$update_dados['password'] = Hash::make($dados['password']);
DB::table('users')->where('id', $dados['id'])->update($update_dados);
You just need to merge to the array with all the values (except the password) the password only if exists / is set:
$your_array = [
'name' => $dados['name'],
'email' => $dados['email'],
'credencial' => $dados['credencial'],
'sobre' => $dados['sobre'],
'updated_at' => Carbon::now(),
];
DB::table('users')->where('id', $dados['id'])->update(
empty($dados['password']) ? $your_array : array_merge($your_array, ['password' => $dados['password']])
);

Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array

I have a model I plan to save the input to two different tables but I have an error
Symfony\Component\Debug\Exception\FatalThrowableError Argument 1
passed to Illuminate\Database\Eloquent\Builder::create() must be of
the type array, object given, called in
C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php
on line 23
the first table is Transaction_in and the second is Transaction_in_detail. I planned to use idTransaction_in as a connector between 2 tables and that column is not a primaryKey (is it a good practice)? I can save the input to Transcation_in table but still failed to save the input to the 2nd table and I don't know how to make the idTransaction_in column as a connector.
public function store(Request $request)
{
$request->validate([
'supplier_name' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_name' => 'required',
'device_brand_name' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_name');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
$lastid=Transaction_in::create($transaction_in)->idTransaction_in;
if(count($request->device_type_name)>0){
foreach ($request->device_type_name as $item => $v) {
$data2=array(
'Transaction_in_id' => $lastid,
'DeviceType_id' => $request->device_type_name[$item],
'DeviceBrand_id' => $request->device_brand_name[$item],
'spek_device' => $request->device_spec[$item],
'harga_device' => $request->price[$item],
'jumlah_device' => $request->amount[$item],
'total_harga_device' => $request->total_price[$item]
);
Transaction_in_detail::insert($data2);
}
}
return redirect('/transactionsin')->with('success', 'Transaction success');
}
The DeviceType_id and Devicebrand_id are foreign key.
As I see you have problem in this line
$lastid=Transaction_in::create($transaction_in)->idTransaction_in;
$transaction_in is object and create method requires array to be passed in.
If everything else is correct this should work:
$lastid=Transaction_in::create($transaction_in->toArray())->idTransaction_in;
You have already save the data, but you use create also. It will create duplicate records in your DB.
I will give you a solution:
$transactionIn = Transaction_in::create([
'idTransaction_id' => '0',
'supplier_id' => $request->input('supplier_name') // why supplier name assigned supplier_id?
'tanggal_transaksi' => $request->input('transaction_in_date'),
]);
$transactionIn = tap($transaction_in)->update([
'idTransaction_in' => sprintf('TIN-%04d', $transactionIn->id)
]);
$lastId = $transactionIn->idTransaction_in;

How to add value into existing array without replacing exists array data? [duplicate]

Here I used updateOrCreate method to post data but when I use this method old data replaced by new data but I want to add new data without updating or replacing exists data.
here is the code for insert data
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id], // match the row based on this array
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => json_encode($seat),
'price' => $request->price,
'profile' => 'pending',
]
);
I solved myself, I stored old data into $extSeat then merge with new data, I don't know the logic is correct or wrong but works
$extSeat = DB::table('bookings')->select('seat')->first();
$extSeat = explode(",", $extSeat->seat);
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],// row to test if schedule id matches existing schedule id
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat )),
'price' => $request->price,
'profile' => 'pending',
]);

Problems with seeds in Laravel

My problem is the next one:
I have already done some seeds, and im trying to get the primary key to the another table/seed.
Here is the code i have problems:
$factory->define(App\Movimento::class,function(Faker\Generator $faker){
$Transportador=App\Transportador::pluck('TransportadorId');
$array =[
'MovimentoId' => $faker->randomNumber,
'Data' => $faker->date,
'Destino' => $faker->word,
'EMExp' => $faker->word,
'Transp' => $faker->randomNumber($Transportador)
];
return $array;
});
So the "Transp" is a Foreign Key and i want the same key has the "TransportadorId" from the other seed.
Here is the code how is clear from errors:
$factory->define(App\Transportador::class,function(Faker\Generator $faker){
$nbDigits='3';
$redDigits='9';
$array =[
'TransportadorId' => $faker->randomNumber($nbDigits),
'Nome' => $faker->text,
'Contribuinte' => $faker->randomNumber($redDigits)
];
return $array;
});
P.S-> I'm sorry for my bad English.
You can probably do:
$factory->define(App\Movimento::class,function(Faker\Generator $faker){
$Transportadores = App\Transportador::all();
$array =[
'MovimentoId' => $faker->randomNumber,
'Data' => $faker->date,
'Destino' => $faker->word,
'EMExp' => $faker->word,
'Transp' => $Transportadores->random()->TransportadorId
];
return $array;
});

Saving one-to-many relationship to DB (laravel)

I'm trying to save a relationship the way I saw on the docs, but isn't working.
On my Contato (Contact) model I've:
public function filhoContato()
{
return $this->hasMany('FilhoContato', 'id_contato');
}
Along with my fillables to enable mass-assignment
My FilhoContato (ContactChildren) model:
public function contato()
{
return $this->belongsTo('Contato');
}
And on my controller:
$contato = Contato::create(array(
'nome' => Input::get('nome'),
'nascimento' => $data,
'cpf' => Input::get('cpf'),
'tel_principal' => Input::get('telefone'),
'idade' => Input::get('idade'),
'email' => Input::get('email'),
'tipo_end' => Input::get('tipo'),
'cep' => Input::get('cep'),
'estado' => Input::get('estado'),
'cidade' => Input::get('cidade'),
'bairro' => Input::get('bairro'),
'rua' => Input::get('rua'),
'numero' => Input::get('numero'),
'logradouro' => Input::get('logradouro'),
'genero' => Input::get('genero'),
'estadoCivil' => Input::get('estadoCivil'),
'mae' => Input::get('mae'),
'pai' => Input::get('pai'),
'filhos' => Input::get('filhos'),
'grupo' => Input::get('grupo'),
'caminho' => $filename . $extension,
'ativo' => Input::get('ativo'),
'exaluno' => Input::get('exaluno')
));
$filhocontato = new FilhoContato(array('nome' => Input::get('name')));
$contato = Contato::find(1);
$filhocontato = $contato->filhoContato()->save($filhocontato);
However only the Contato (contact) table data gets inserted.
How can I save both tables at same time? I need a loop to get all value from Input::get('name') too.
Just to clarify, if my Contato(contact) has a children then he will insert their names in a dynamically generated form text field and when he clicks submit all of his data will go to Contato(contact) table and his children (if he has) will go to filhocontato table which structure is (id, nome, id_contato). That's what I'm aiming for at least :/

Categories