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 :/
Related
i'm implementing an online payment platform similar to paypal, the problem is that when they click on the buy button 2 times or more quickly and this causes the payment to register twice instead of once
When you click buy execute this action:
public function invoke(Request $request) {
$payment_id = $request->get('payment_id');
$credenciales = config('services.mercadopago.token');
$request->get('user_id'));
$response = Http::get("https://api.mercadopago.com/v1/payments/$payment_id" . "?access_token=$credenciales");
$response = json_decode($response);
$request->session()->put('order', $response->order->id);
$request->session()->put('ingreso', $response->transaction_details->net_received_amount);
$request->session()->put('monto', $response->transaction_details->total_paid_amount);
$request->session()->put('method', $response->payment_type_id);
$status = $response->status;
If the answer is approved run this:
if($status == 'approved') {
Income::insert([
'user_id' => Session::get('user_id'),
'evento_id' => Session::get('variableName'),
//Guardar el personal seleccionado
'mp_id' => Session::get('order'),
'metodo' => Session::get('metodo'),
'monto' => Session::get('monto'),
'rrpp_id' => Session::get('rrpp'),
'ingreso' => Session::get('ingreso'),
]);
OrderNew::insert([
'user_id' => Session::get('user_id'),
'dia_id' => Session::get('variableName'),
//Guardar el personal seleccionado
'whatsapp' => Session::get('telefono'),
'cantidad' => Session::get('cantidad'),
'anticipada' => Session::get('anticipada'),
'horario' => Session::get('horario'),
'rrpp' => Session::get('rrpp'),
'pagado' => '1',
'tipo' => 'vip',
'codigo' => rand(1580, 4005),
]);
in the first model I register the incoming money and in the second model I register the customer's order
and there is the problem, if they click on Buy several times, the records are duplicated and they get free products
How can I limit or solve this problem?
Instead of Insert use updateOrCreate or maybe firstOrCreate that accepts 2 parameters, first one an array to check the values against database records and second to insert/find data. If the records match, it will be updated/retrieved, otherwise a new one will be created. Please check Laravel docs for updateOrCreate or firstOrCreate.
In your case, for example:
Income::firstOrCreate([
'user_id' => Session::get('user_id'),
'evento_id' => Session::get('variableName'),
//Guardar el personal seleccionado
'mp_id' => Session::get('order'),
'metodo' => Session::get('metodo'),
'monto' => Session::get('monto'),
'rrpp_id' => Session::get('rrpp'),
'ingreso' => Session::get('ingreso'),
]);
This will check the exact records and if it finds a match it retrieves the data, otherwise creates one which avoids duplicated entries.
However, since your second query has a random number generated, it will not find a match if we pass only one arguement, therefore, as a first arguement we need to pass the array to be checked against the database (all data, except for the rand() part).
OrderNew::firstOrCreate(
[
'user_id' => Session::get('user_id'),
'dia_id' => Session::get('variableName'),
//Guardar el personal seleccionado
'whatsapp' => Session::get('telefono'),
'cantidad' => Session::get('cantidad'),
'anticipada' => Session::get('anticipada'),
'horario' => Session::get('horario'),
'rrpp' => Session::get('rrpp'),
'pagado' => '1',
'tipo' => 'vip',
],
[
'user_id' => Session::get('user_id'),
'dia_id' => Session::get('variableName'),
//Guardar el personal seleccionado
'whatsapp' => Session::get('telefono'),
'cantidad' => Session::get('cantidad'),
'anticipada' => Session::get('anticipada'),
'horario' => Session::get('horario'),
'rrpp' => Session::get('rrpp'),
'pagado' => '1',
'tipo' => 'vip',
'codigo' => rand(1580, 4005),
]);
According to your data, you can change the array of data to be checked against the database.
Specify that the route should not allow concurrent requests from the same session.
Route::get('/deposit',ExampleController::class)->block(10);
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
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;
i have been trying to create a very simple form for a drupal site, the form displays all fields correctly. when trying to save the information to the database however i get an error.
i get: PHP Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) on line 286
i have been looking at severel guides on how to save data in drupal, and all agree that i should be using db_insert instead of a db_query with an insert statement, but for the life of me, i can't understand why i get this error. i have been looking at several examples including;
https://www.drupal.org/node/1164398
can anyone tell me why it isnt saving? and im getting the error?
function drupalform_form1_submit($form, &$form_state) {
$values = array(
// CONTACT INFO
'email' => $form_state['values']['email'],
'phone' => $form_state['values']['phone'],
// PARTICIPANT 1 VALUES
'p1name' => $form_state['values']['p1name'],
'p1nationality' => $form_state['values']['p1nationality'],
'p1University' => $form_state['values']['p1University'],
'p1year' => $form_state['values']['p1year'],
// PARTICIPANT 2 VALUES
'p2name' => $form_state['values']['p2name'],
'p2nationality' => $form_state['values']['p2nationality'],
'p2University' => $form_state['values']['p2University'],
'p2year' => $form_state['values']['p2year'],
// PARTICIPANT 3 VALUES
'p3name' => $form_state['values']['p3name'],
'p3nationality' => $form_state['values']['p3nationality'],
'p3University' => $form_state['values']['p3University'],
'p3year' => $form_state['values']['p3year'],
// PARTICIPANT 4 VALUES
'p4name' => $form_state['values']['p4name'],
'p4nationality' => $form_state['values']['p4nationality'],
'p4University' => $form_state['values']['p24niversity'],
'p4year' => $form_state['values']['p4year']
);
$insert = db_insert('bte_handin')->fields(array(
// INSERTING CONTACT INFO
'email' => $values['email'],
'phone' => $values['phone'],
// INSERTING PARTICIPANT 1
'p1name' => $values['p1name'],
'p1nationality' => $values['p1nationality'],
'p1University' => $values['p1University'],
'p1year' => $values['p1year'],
// INSERTING PARTICIPANT 2
'p2name' => $values['p2name'],
'p2nationality' => $values['p2nationality'],
'p2University' => $values['p2University'],
'p2year' => $values['p2year'],
// INSERTING PARTICIPANT 3
'p3name' => $values['p3name'],
'p3nationality' => $values['p3nationality'],
'p3University' => $values['p3University'],
'p3year' => $values['p3year'],
//INSERTING PARTICIPANT 4
'p4name' => $values['p4name'],
'p4nationality' => $values['p4nationality'],
'p4University' => $values['p4University'],
'p4year' => $values['p4year'],
))->execute(); This is where the error is occuring
drupal_set_message("Your answer has ben saved");
}
I'm not sure if the title of this question is necessarily the accurate description of what I need to do, but I'll go ahead and ask my question and see what everyone thinks...
Basically, I am receiving data from a source that I have no control over, and I need to transpose it into a suitable format for inserting into my database using CakePHP. So, here's how I'm doing it:
public function submitApp($data) {
$array = array(
'Student' => array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'address' => $data['address'],
'dob' => $data['dob'],
'gender' => $data['gender']
),
'Application' => array(
'course_id' => $data['course_id'],
'question1' => $data['question1'],
'question2' => $data['question2'],
'question3' => $data['question3'],
'question4' => $data['question4'],
),
'ApplicationQualification' => $data['Qualifications']
);
// Logic to save $array goes here
}
The problem is that sometimes not all of the keys in $data will be submitted to my app but I still want my app to work with what it gets.
I know that I can wrap each key in a conditional like this:
if (!isset($data['name'])) { $data['name'] = null; }
...and then building the array, but this seems like a pretty clumsy way of doing it. Is there a more efficient way to do this?
You could use a simple ternary statement
'name' => array_key_exists('name', $data) ? $data['name'] : null
Alternatively, you can set up a default array and then merge the given values in
$defaults = [
'name' => null,
'email' => null,
// etc
];
$data = array_merge($defaults, $data);