Property [associated_occupation] does not exist on this collection instance. - Laravel - php

I would like to store a database value into the variable. For some reason It's not working as expected. Below is the code in controller:
public function show(Word $word)
{
//
$curriculum = Curriculum::findOrFail($word->id);
// dd($curriculum->id);
session(['key' => $curriculum->id]);
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->get();
$information = Information::where('curriculum_id','=', $word->id)->get();
$practical = Practical::where('curriculum_id','=',$word->id)->get();
$work = Work::where('curriculum_id','=',$word->id)->get();
$entry = Entry::where('curriculum_id','=',$word->id)->get();
$assessment = Assessment::where('curriculum_id','=',$word->id)->get();
$parts = Part::where('curriculum_id','=',$word->id)->get();
$occupurpose = Occupurpose::where('curriculum_id','=',$word->id)->get();
$occutask = Occutask::where('curriculum_id','=',$word->id)->get();
$taskdetail = Taskdetail::where('curriculum_id','=',$word->id)->get();
$purposekm = Purposekm::where('curriculum_id','=',$word->id)->get();
$guidedtopic = Guidetopic::where('curriculum_id','=',$word->id)->get();
$purposepms = Purposepm::where('curriculum_id','=',$word->id)->get();
$purposewem = Purposewem::where('curriculum_id','=',$word->id)->get();
$guidedpmstopics = Guidedpmstopic::where('curriculum_id','=',$word->id)->get();
$guidedwemstopics = Guidedwemstopic::where('curriculum_id','=',$word->id)->get();
$wordTest = new \PhpOffice\PhpWord\PhpWord();
$newSection = $wordTest->addSection();
$SectionHeading = "SECTION 1: CURRICULUM SUMMARY";
$newSection->addText($SectionHeading);
$topicHeading = "1. Occupational Information";
$newSection->addText($topicHeading);
$subTopic = "1.1 Associated Occupation";
$newSection->addText($subTopic);
$newSection->addText($knowledge->associated_occupation);
$occupationTopic = "1.2 Occupation or Specialisation Addressed by this Curriculum";
$newSection->addText($occupationTopic);
$newSection->addText($knowledge->specialisation);
$alternativeTopic = "1.3 Alternative Titles used by Industry";
$newSection->addText($alternativeTopic);
$newSection->addText($knowledge->alternative_title);
$objectWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordTest,'Word2007');
try {
$objectWriter->save(storage_path('TestWordFile.docx'));
} catch(Exception $e) {
}
return response()->download(storage_path('TestWordFile.docx'));
}
When I do dd of the curriculum id and the knowledge result I get correct feedback. Now I would like to store the column
associated_occupation
into the variable called newSection but I get the error mentioned on the subject. I also tried
$newSection->addText($knowledge->select('associated_occupation')); instead of $newSection->addText($knowledge->associated_occupation);
Please assist.

You are trying to access a property of a collection:
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->get();
The above will give you a collection of results that have the curriculum_id as $word->id
https://laravel.com/docs/5.6/queries#retrieving-results
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object.
So when you do:
$newSection->addText($knowledge->associated_occupation);
The $knowledge->associated_occupation is looking for associated_occupation on a collection of results rather than a specific Knowledge
Change your query to:
$knowledge = Knowledge::where('curriculum_id','=', $word->id)->first();
To get the first Knowledge that has it's curriculum_id as $word->id
https://laravel.com/docs/5.6/queries#retrieving-results
If you just need to retrieve a single row from the database table, you
may use the first method. This method will return a single StdClass
object:
Or filter the collection and pick a specific one

Related

Update One JSON Field in Database - CodeIgniter

I have a JSON field called 'spec' and there are about 10 other items in this in JSON format. I need to only update the quantity.
Although when I try this method, it deletes everything else in it and just sets spec = quantity.
Heres what I have so far.
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
foreach ($coupon_array as $row) {
$spec = json_decode($row['spec'], true);
}
$quantity_new = $spec['quantity'] - 1;
$data2 = array(
'spec' => json_encode(array(
'quantity'=> $quantity_new
)));
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $data2);
You need to overrite only this one field and update whole field in query.
<?php
$pass_coupon_id = $this->pass_coupon_id();
$coupon_array = $this->db->query("SELECT * FROM coupon WHERE coupon_id='$pass_coupon_id'")->result_array();
// i don't know what you're using, but using foreach to extract single row isn't good solution. Look for sth like result_row() maybe.
$coupon = $coupon_array[0];
$spec = json_decode($coupon, true);
$new_quantity = $spec['quantity'] - 1;
$spec['quantity'] = $new_quantity;
$new_spec = json_encode($spec);
$this->db->where('coupon_id', $pass_coupon_id);
$this->db->update('coupon', $new_spec);
Depending on the database, the best solution would be using specific function to ommit updating whole structure - https://stackoverflow.com/a/34987329/2926214

Filling a two dimensional array with mysql fetch results in php

I just had a framework for creating charts and this is how it works normally.
$p = new chartphp();
$p->data = array(array(
array("A",2),
array("B",3),
array("C",23),
array("D",10)
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
This way it works perfectly fine, now I need to get results from a sql query and fill the array.
$query ="SELECT t.date AS dates,COUNT(t.id) AS trans FROM Gab AS g, Transaction AS t WHERE t.date BETWEEN '2015-07-30' AND '201-07-10' AND g.TID = '1401009' ORDER BY DATES";
$ask = mysql_query($query) or die("Error");
//Now I try to load the results into the array to be integrated into the API.
$p = new chartphp();
$p->data = array(array(
while($recon = mysql_fetch_array($ask)
{
array($recon['dates'],recon['trans']),
}
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
I tried this but it does not work, the array dont seem to be loaded !
I'm actually not sure what nesting a while like you have would do and I'm unable to experiment at the moment, but something like this should get you in the right direction:
$p->data = array(array());
while($recon = mysql_fetch_array($ask))
{
$p->data[0][] = array($recon['dates'], $recon['trans']);
}
Initializing the array and then appending the elements in the loop.

FLOT - Fluid / Dynamic Charts - PHP MYSQL

I am trying to Plot a Graph with FLOT but I cant get my head around how to get make it Dynamic with multiple series.
I am trying to get Race Data , Eg Laps and Time as the Graph x and y, but also trying to get the Race ID as a new series line for each Rider.
I have tried it at a Loop for each RaceID, and I have tried it as a multidimensional array, But I cant get my head around how to get it formatted to how FLOT wants it.
I can get it to work with 1 Rider:
$GetLapData = mysql_Query("SELECT LapData.*, u.RaceID
FROM `LapData`
left join User as u on LapData.TagID = u.TagID
Where LapData.EventID = '$EventID'
and LapData.RaceNameID = '$RaceNameID'
and LapData.TagID = '$RacingNumber'
ORDER BY `LapData`.`LapNumber` ASC");
while ($row = mysql_fetch_assoc($GetLapData))
{
$dataset1[] = array($row['LapNumber'],$row['LapTimeinSeconds']);
}
and then plot the single Data Set
$(function() {
var d1 = <?php echo json_encode($dataset1) ?>;
$.plot("#placeholder", [ d1 ]);
});
Any Ideas on making it all riders for the Race would be really helpful.
This is a tough question to answer without seeing your database scheme, but I'll give it a shot.
First, let's modify your SQL statement. I'm guessing that this part and LapData.TagID = '$RacingNumber' is what subset's it down to a single rider? Also, what's the purpose of the join, do you want the rider's name from there or some other identifier? I've left it but if you aren't using it, it's a waste...
$GetLapData = mysql_Query("SELECT LapData.TagID, LapData.LapNumber, LapData.LapTimeInSeconds
FROM LapData
LEFT JOIN User AS u ON LapData.TagID = u.TagID
WHERE LapData.EventID = '$EventID'
ANDLapData.RaceNameID = '$RaceNameID'
AND LapData.TagID = '$RacingNumber'
ORDER BY LapData.TagID, LapData.LapNumber ASC");
$allSeries = array(); // our "return value"
$currentSeries = null; // some temp variables
$currentRider = null;
while ($row = mysql_fetch_assoc($GetLapData))
{
$loopRider = $row['TagID']; // get rider for this database row
if ($currentRider === null || $loopRider != $currentRider) // if first loop or new rider
{
if ($currentSeries !== null)
{
$allSeries[] = $currentSeries; // we have a new rider push the last one to our return array
}
$currentSeries = array(); // this is first loop or new rider, re-init current series
$currentSeries["label"] = $loopRider;
$currentSeries["data"] = array();
}
$currentSeries["data"][] = array($row['LapNumber'],$row['LapTimeinSeconds']); //push row data into object
}
$allSeries[] = $currentSeries; // last rider's data push
In the end, allSeries is an array of associative arrays per flots documentation.
Mainly:
$allSeries = [{
"label" = "tag1",
"data" = [[0,12],[1,45],[2,454]]
},{
"label" = "tag2",
"data" = [[0,122],[1,415],[2,464]]
}]
After you Json encode this, the call is:
$.plot("#placeholder", allSeries);
My Standard PHP disclaimer, I'm not a PHP programmer, I've never used it and never ever want to use it. All the above code was peiced together from quickly reading the documentation and is untested.

PHP / Zend / Google Spreadsheet not getting all rows

I am trying to get all the rows from a Google spreadsheet via a PHP/Zend script. This is the script I am using:
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient('xxxxxxxxx', 'xxxxxxx', $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
// Get spreadsheet key
$spreadsheetsKey = 'xxxxxxxxxxxxx';
$worksheetId = 'xxx';
// Get cell feed
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetsKey);
$query->setWorksheetId($worksheetId);
$cellFeed = $spreadsheetService->getCellFeed($query);
// Build an array of entries:
$ssRows = array();
$ssRow = array();
$titleRow = array();
$tableRow = 1;
foreach($cellFeed as $cellEntry) {
$row = $cellEntry->cell->getRow();
$col = $cellEntry->cell->getColumn();
$val = $cellEntry->cell->getText();
// Add each row as a new array:
if ($row != $tableRow) {
array_push($ssRows, $ssRow);
$ssRow = array();
// Move to the next row / new array
$tableRow = $row;
}
// Build the array of titles:
if ($row == 1) {
$titleRow[$col] = $val;
}
// Build the array of results with the title as the key:
else {
$key = $titleRow[$col];
$ssRow[$key] = $val;
}
}
// Pass the results array:
return array_reverse($ssRows);
This builds me an array with MOST of the details from the spreadsheet, however it always misses off the last entry - can anyone see what I am doing wrong, or is there a better way to get all the data from the spreadsheet?
The form is a 3 part form, based on different answers. On filling out one part, I want to display a URL back to the form, with some details from the first form pre-filled to make the second part of the form faster to fill out. This is all fine, it is simply the missing last entry that is the major problem!
Thanks!
Your code works like this:
if (next_row) {
data[] = current_row
current_row = array();
}
if (first_row) {
title_row logic
} else {
add cell to current_row
}
So you only add the rows to your collector once you go to the next row. This will miss the last row because you'll miss that last transition.
The easy fix is to add array_push($ssRows, $ssRow); right after the foreach loop. You will need to add a check for 0 rows, this should be skipped then.
Perhaps a more proper fix is to iterate by row, then by cell, rather than just by cell.

Sort LastUpdateTime not working quickbooks API PHP

I am getting the below error when i tried to retrieve Objects with the Simple Query in Quickbooks.
Invalid Property Name in Sort Criteria: LastUpdatedTime
BAD_QUERY_REQUESTQUERY_INVALID_SORT_CRITERIA
I tried to sort using name and some other values, its working but for CreateTime and LastUpdatedTime, its not working.
Used the below function to get the Quickbooks Vendors
QuickBooks_IPP_Service_Vendor
Query used to retrieve in order:
PageNum=1&ResultsPerPage=50&Sort=LastUpdatedTime OldestToNewest
Response:
Invalid Property Name in Sort Criteria: LastUpdatedTime
BAD_QUERY_REQUESTQUERY_INVALID_SORT_CRITERIA
Looking at the documentation:
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/0100_calling_data_services/0030_retrieving_objects
It appears as if you're trying to sort by a field that doesn't exist.
Are you sure you didn't mean:
LastUpdatedTime
Instead of:
LastUpdateTime
My Code and Response
Code:
$ServiceName = "QuickBooks_IPP_Service_".$module;
$Service = new $ServiceName();
if ($creds['qb_flavor'] == QuickBooks_IPP_IDS::FLAVOR_ONLINE)
{
$qbmodule = "QB".$module;
$updatedtime = getLastSyncDetails($qbmodule);
$query = "";
if(!empty($updatedtime) && trim($updatedtime) != '')
{
$time = str_replace(" ", "T", $updatedtime);
$time = $time."-07:00";
$query = array('Sort' => 'LastUpdatedTime OldestToNewest');
}
}
$list = array();
$responseQuery = array();
$responseQuery = $Service->findAll($Context, $realm, $query, $page, $limit);
Response
Content-Type: application/xml
Invalid Property Name in Sort Criteria: LastUpdatedTime
BAD_QUERY_REQUEST
QUERY_INVALID_SORT_CRITERIA

Categories