Laravel: How do I insert a multidimensional array in the controller - laravel

Table:
this is the table being used from the SQL database (id is auto incremented)
Array:
then output below is from the console of the browser after adding in: dd($replies);
The screenshot below shows the input of the ui, which is the same data registered in the array in the screenshot above
Entities:
The function below is being used to create/insert the data
public function create($payload_reply)
{
return rescue(function() use($payload_reply){
return self::insert($payload_reply);
});
}
Controller:
My issue is with my code below
if($result){
$replies = $request->get('reply');
dd($replies);
$payload_reply = [];
foreach($replies as $reply){
$payload_reply = [...$payload_reply, [
'id' => $request->get('group_id'),
'message_id' => $request->get('message_id'),
'parent_id' => $request->get('message_id'),
'reply' => $request->get('reply'),
'reply_type' => $request->get('reply_type'),
'reply_description' => $request->get('reply_description')
]];
}
$result = $this->bbrMessageTemplate->create($payload_reply);
}
This code does not insert the array in my table. I tried a for each loop in order for each data to be inserted one at a time until all have been inserted. What did I do wrong? I am not sure if it is the array or the for each.
Any help would be appreciated.
Clarifications: my variable $result works fine, so it leads to this if statement which is my main issue.

Related

Pass data from controller to View in Laravel

I have a query that I am not able to pass to the view.
$dias_usados = calendario::where('id_funcionario', '=', $userid)
->groupBy('id_funcionario')
->sum('contaferias');
dd outputs the correct expected value.
I tried to pass to the View as follows:
return view(
'ausencia',
compact('tabela'),
['itens' => $ferias],
['dias_usados' => $dias_usados]
);
I'm having problems with the last one dias_usados. The first two work normally.
<h3>{{$dias_usados}}</h3>
Causes the following error:
Undefined variable: "dias_usados"
I also leave the path I have on the route, but I don't see anything wrong
Route::get('Ausencia', [AusenciaController::class, 'index'])->name('ausencia.index');
This is the the definition of the view helper
function view($view = null, $data = [], $mergeData = []) { }
You are misusing the function by giving it three separate arrays expecting it to get them as $data.
Fixes
return view('ausencia', [
'tabela' => $tabela,
'itens' => $ferias,
'dias_usados' => $dias_usados,
]);
return view('ausencia')
->with(compact('tabela'))
->with(['itens' => $ferias])
->with(['dias_usados' => $dias_usados]);
return view(
'ausencia',
array_merge(
compact('tabela'),
['itens' => $ferias],
['dias_usados' => $dias_usados]
)
);

Why Laravel does not recognize recently added records in a table

I am doing following 3 steps:
Inserting records from Master table to Temp table
Displaying Temp table in Data table
Editing records in Data table and updating Mem table.
So, Step 1 no issue, I am able to insert records in Temp table using Model::Create command.
Step 2 no issue, I am able to bring these records to Data table as well and can see these newly inserted records in temp table in MySQL as well.
Issue is with step 3. When I click the edit button on data table, It gives an error
"message": "Attempt to read property "PMDTDUniqueId" on null",
So it is not recognizing the newly inserted records even when I can see it in enter code hereMySQL and Data table.
Why it should behave like this?
Any help will be appreciated.
// Inserting Records from Master table to Temp Table
public function PMDTH11AppendMemTableTrait()
{
$loginName = Auth::user()->name;
// Delete Records for this user first
MemIncomeType::where('PMDTDUser', $loginName)->delete();
$Master = IncomeType::orderBy('PMITHUniqueId')->get();
$LineNo = 10;
foreach ($Master as $key => $value) {
MemIncomeType::create([
'PMDTDUniqueIdH' => $LineNo,
'PMDTDIncomeId' => $value->PMITHIncomeId,
'PMDTDIncomeIdK' => $value->PMITHIncomeIdK,
'PMDTDDesc1' => $value->PMITHDesc1,
'PMDTDIsSelect' => 0,
'PMDTDDedPercent' => 100,
'PMDTDUser' => $loginName
]);
$LineNo++;
}
}
// Editing Record that are newly inserted as above
public function PMDTH11FethchEditedSubFormDataTrait($request)
{
$PMDTDUniqueId = $request->input('id');
$MemIncomeType = MemIncomeType::find($PMDTDUniqueId);
// $MemIncomeType = MemIncomeType::where('PMDTDUniqueId', $PMDTDUniqueId)->get();
// echo 'Data Submitted.';
// echo "<pre>";
// print_r($MemIncomeType);
// die();
return $output = array(
'PMDTDUniqueId' => $MemIncomeType->PMDTDUniqueId,
'PMDTDIncomeId' => $MemIncomeType->PMDTDIncomeId,
'PMDTDDesc1' => $MemIncomeType->PMDTDDesc1,
'PMDTDDedPercent' => $MemIncomeType->PMDTDDedPercent
);
}
In the above function 'PMDTH11FethchEditedSubFormDataTrait' I am getting the error.
The model I declared for MemIncomeType
namespace App\Models\Payroll\IncomeDeductionType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class MemIncomeType extends Model
{
use HasFactory;
public $timestamps = false;
protected $table = 'zmem11906l0211';
protected $primaryKey = 'PMDTDUniqueId';
protected $fillable =
[
'PMDTDUniqueId',
'PMDTDUniqueIdH',
'PMDTDIncomeId',
'PMDTDIncomeIdK',
'PMDTDDesc1',
'PMDTDIsSelect',
'PMDTDDedPercent',
'PMDTDUser',
];
}

Encrypted Array Won't Save in Eloquent Model

I'm having an odd error with saving an encrypted array in Laravel. The model never updates even when save() is called.
There are no console or SQL errors.
When the encryption is disabled, there are no errors and the model updates successfully.
In a Controller, I'm calling the model like so:
$userData = UserData::where('user_id', $user_id)->first();
I then pull the array:
$encryptedData = $userData->app_data;
And I want to add to this array e.g.
$encryptedData['new'] = 'axy';
$encryptedData['time'] = time();
I then update the model and save it:
$userData->app_data = $encryptedData;
$userData->save();
However, here is where the problem starts. The model does not update. It remains as if nothing happens. Hence if I refresh(), I get the same data as if I had never added the two new entries. When I log it, it looks like this:
Array
(
[token] => xyz
[access_token] => abc
)
After the addition of two new entries:
Array
(
[token] => xyz
[access_token] => abc
[new] => 'axy'
[time] => 1234
)
And after the save() and refresh():
Array
(
[token] => xyz
[access_token] => abc
)
The model looks like this:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Contracts\Encryption\DecryptException;
class UserData extends Model
{
protected $fillable = [
'user_id', 'app_data'
];
protected $casts = [
'user_id' => 'int',
'app_data' => 'array'
];
public function getAppDataAttribute($value)
{
try {
return decrypt($value);
}
catch (DecryptException $e) {
return $value;
}
}
public function setAppDataAttribute($value)
{
$this->attributes['app_data'] = encrypt($value);
}
}
Why are my additions to the array not being saved?
Edit: The strangeness continues
If I call:
UserData::where('id', $userData->id)->update(['app_data' => $encryptedData]);
Then the model does update and does not encrypt, HOWEVER, when I refresh and log the new 'app_data' field, it is returned as a JSON string and not an array as before. I need to cast/decode it to an array each time I want to use it.
Couple of things to look for.
1) The Laravel encrypter uses the app key. Make sure you have one in your .env file. If not, run php artisan key:generate
2) I assume the array is correctly formatted like this:
Array
(
'token' => 'xyz', // You have a = here and no commas after any other value
'access_token' => 'abc'
)
3) Depending on what you are storing this as, you can test by serializing the array before encrypting it:
$arr = serialize($encryptedData); // After you have added new data to the array
$userData->app_data = $arr;
$userData->save();
This is automatic in Laravel, but may give you a help hunting the bug. Test with your mutator using encryptString() and manually unserialize / decryptString() to see if any odd behavior by stepping through the values as they are mutated.

Laravel5.3 maatwebsite/excel Read value from excel & insert into database

Here is my Excel data sheet type:
Here is My Table Schema:
Here is my method to import data:
public function saveActivationInfoExcel(Request $request)
{
if($request->hasFile('import_file')){
$path = $request->file('import_file')->getRealPath();
$data = Excel::load($path, function($reader) {})->get();
if(!empty($data) && $data->count()){
foreach ($data->toArray() as $key => $value) {
if(!empty($value)){
foreach ($value as $v) {
$insert[] = [
'mobile_no' =>$v['mobile_no'],
'model' => $v['model'],
'serial_1' => $v['serial_1'],
'serial_2' => $v['serial_2'],
'activation_date' => $v['activation_date'],
];
}
}
}
dd($insert);
if(!empty($insert)){
//ProductActivationInfo::insert($insert);
return back()->with('success','Insert Record successfully.');
}
}
}
return back()->with('error','Please Check your file, Something is wrong there.');
}
Now my problem is, when I try to import data I got this dd($insert) error
Illegal string offset 'mobile_no'
'serial_1' => '3.5194508009307E+14',
'serial_2' => '3.5194508009307E+14',
'activation_date' => object(Carbon), null)
have a look both serial_1 & serial_2 showing different value rather then actual excel value. also activation_date value is null.
would appreciate your valuable suggestion to solve this regarding reading data using "maatwebsite/excel" laravel library.
Please use the CSV file to import data and change the serial_1 and serial_2 column format as a fraction. And change the format of activation_date column.
Thanks

Quickbase delete_record

I am unable to get delete_record function to work. Here is the delete_record code that I am currently using:
$qb->db_id = $myQbTables["table1"]; //using table 1 now
$queries = array( //this is the where clause now for the delete query
array(
'fid' => '12',
'ev' => 'EX',
'cri' => '1175'
),
array(
'fid' => '8',
'ev' => 'EX',
'cri' => $Child_ID
)
);
$results = $qb->do_query($queries, '', '', 'a', '1', 'structured', 'sortorder-A'); //get all results
if($results->errCode !== 0) {
echo $results->errTxt;
}
print_r($results);
foreach($results->table->records->record as $record){ //getting results of delete query
$Deletevar = $record->f[11];
$deleted = $qb->delete_record($Deletevar); //deleting results
print_r($deleted);
}
I know that the 'cri' matches things in my quickbase but I can't seem to use f[3] (the record id) to delete it!
NOTE
I have found the main issue I was having! If you are making API calls using the QB API, delete records and purge records does not include the app token!! Please use the following code to update the delete_records function!!!!
public function delete_record($rid) {
if($this->xml) {
$xml_packet = new SimpleXMLElement('<qdbapi></qdbapi>');
$xml_packet->addChild('rid',$rid);
$xml_packet->addChild('ticket',$this->ticket);
$xml_packet->addChild('apptoken',$this->app_token);
$xml_packet = $xml_packet->asXML();
$response = $this->transmit($xml_packet, 'API_DeleteRecord');
}
else {
$url_string = $this->qb_ssl . $this->db_id. "?act=API_DeleteRecord&ticket=". $this->ticket
."&apptoken=".$this->app_token."&rid=".$rid;
$response = $this->transmit($url_string);
}
return $response;
}
I think you may be missing something in your query. If you're trying to get a list of records where the field 12 is 1157 and field 8 is equal to $Child_ID you'll need to add AND into your query. When using the API in a URL the query would be &query={12.EX.1175}AND{8.EX.77} if, for example, the child ID were 77. To do that in the PHP SDK for Quickbase you add 'ao' => 'AND' to all arrays following the first query array. Try updating your $queries array to this:
$queries = array( //this is the where clause now for the delete query
array(
'fid' => '12',
'ev' => 'EX',
'cri' => '1175'
),
array(
'ao' => 'AND', // Saying that 12.EX.1175 AND 8.EX.$Child_ID
'fid' => '8',
'ev' => 'EX',
'cri' => $Child_ID
)
);
My PHP skills aren't particularly good, but you'll need to do a bit more to get the record ID#. In the original code, I think that $record->f[3] will just return to SimpleXMLObject for the third field in the array. That won't necessarily be field ID 3 (the record ID). You can either choose to not use the structured format (and change all of your code to match) or add a loop that goes through all the fields and deletes when it reaches the field with id 3:
foreach($results->table->records->record as $record){ //getting results of delete query
//Loop through all fields to find id 3
foreach($record->f as $field){
if($field['id'] == "3"){
$Deletevar = $field['id'];
$deleted = $qb->delete_record($Deletevar); //deleting result
print_r($deleted);
break; //Stops this loop since FID 3 was found
}
}
}
Some performance notes: If you aren't using any other fields, you can set your query to only return record IDs by passing a clist that is just '3'. Also, each delete_record() is a separate API call. There is another method purge_records that allows you pass a query and Quickbase deletes all of the records that match your query. You may want to look into using purge_records() because you can you use it in place of your do_query() and avoid all the loops. It uses fewer of your resources and Quickbase's to process as well.

Resources