This question already has answers here:
Trying to get property 'id' of non-object
(4 answers)
Closed 2 months ago.
The following are the function that I am trying to make work. I think I have the information required correct and the corresponding data also exist in the table but it is showing the error as above. Below are the function in my UserProfileController.
I've tried to change the column name from created_at to date_checkIn but it is showing the same error, both the columns exist in the database table as shown in my screenshots above. Please help
public function userClockOut(Request $r)
{
$result = [];
$result['status'] = false;
$result['message'] = "something error";
$users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'date_checkIn', 'time_checkOut', 'location_checkOut'])->first();
$tt = AttendanceRecord::find($r->tt);
$tt2 = AttendanceRecord::find($r->tt2);
$tz = $tt->created_at;
$tz2 = $tt2->updated_at;
$date = Carbon::createFromFormat('Y-m-d', $tz, 'UTC');
$time = Carbon::createFromFormat('H:i:s', $tz2, 'UTC');
$date->setTimezone('Asia/Singapore');
$time->setTimezone('Asia/Singapore');
$users->date_checkIn = $date;
$users->time_checkOut = $time;
$users->location_checkOut = $r->location_checkOut;
// Save the updated data to the database
AttendanceRecord::updateOrCreate(
['staff_id' => $users->staff_id, 'date_checkIn' => $date],
$users->toArray()
);
$result['data'] = $users;
$result['status'] = true;
$result['message'] = "suksess add data";
return response()->json($result);
}
Screenshots to show that the column exist in the database table :
https://paste.pics/f6103e8822c01f26bd23d500e0b0e9ad https://paste.pics/008df0256fd5ec20caff3772194cc0cf https://paste.pics/66cca657a49944e8087451c3b75967d3
It looks like your $tt = AttendanceRecord::find($r->tt); doesn't return any value so its throwing an error. To solve this first you need to make sure that the $r->tt has a value and that value exists in the database. Next is to avoid that error instead of using the find() method you should use the findOrFail() which will return a 404 status code if the given id do not exist in the database.
$tt = AttendanceRecord::findOrFail($r->tt);
$tt2 = AttendanceRecord::findOrFail($r->tt2);
Also make sure that the $r->tt is the primary key of the table and also make that there's a tt attribute in your form
$tt or $tt2 doesnot found.
$tt = AttendanceRecord::find($r->tt);
$tt2 = AttendanceRecord::find($r->tt2);
Related
basically i have three tables,
sms_content,
sms_content_cities,
sms_content_categories,
sms_content has foregin key in both other tables. i want to save record in these tables at once.
Like i want to save sms_content_id in other tables which are sms_content_cities and sms_content_categories.
Here is my code:
$model = new SmsContent();
$model->version = 0;
$model->sms_from = 1;
$model->sms_text = $inputs['sms_text'];
$date = strtotime($inputs['start_date']);
$startDate = date("Y-m-d H:i:s", $date);
$noteID = $date;
$model->start_date = $startDate;
$endDate = date("Y-m-d", strtotime($inputs['end_date']));
$model->end_date = $endDate;
$model->title_audio = (isset($inputs['title_audio'])) ? $inputs['title_audio'] : "";
$model->audio = (isset($inputs['audio'])) ? $inputs['audio'] : "";
$model->enabled = 1;
$model->ivr_enabled = 1;
$model->note_id = DB::raw($noteID);
$model->sort_order = 0;
$model->save();
this code is saving my in sms_content table , but i dont know how to save his values in other table, like i want to save sms_content "Id" in other tables as a foregin key.
After creating a record in the database, you can access its id immediately like the following:
$model->id
Now as you can access it, just create a new object of other Model and save it there.
As soon as you do $model->save(), an id is saved in the $model collection. You can simply access it using $model->id.
Try dd($model->id); after save() statement.
You can access model properties as soon as you save them in your database. In order to update your other models with data an id you need, you can simply do something like this:
$model1 = new SmsContent();
$model1->version = 0;
$model1->sms_from = 1;
//... and so on
$model1->save();
$model2 = new Model2();
$model2->sms_content_id = $model1->id;
//... and so on
$model2->save();
$model3 = new Model3();
$model3->sms_content_id = $model1->id;
//... and so on
$model3->save();
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
I am trying to get last inserted id in cake php 3.
if($this->request->is('post')){
$this->loadModel('MyPlaylists');
$playlistData = [];
$playlistData["user_id"] = $_POST['user_id'];
$playlistData["play_list_name"] = $_POST['play_list_name'];
$playlistData["section"] = $_POST['section'];
$playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
$playlistData["status"] = 'active';
$playlist_en = $this->MyPlaylists->newEntity();
$this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$this->MyPlaylists->save($playlist_en);
$id=$this->MyPlaylists->id;
}
I have also tried:
$id=$this->MyPlaylists->lastInsertedId;
But it is giving error as below screenshot:
Your code needs some fine tuning.
$playlist_en = $this->MyPlaylists->newEntity();
$playlist_en = $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid = $this->MyPlaylists->save($playlist_en);
if ($isValid) {
$id = $playlist_en->id;
debug($id); // Check your last insert id
} else {
pr($playlist_en->errors()); // Check errors
}
Make a query selecting the first element of the query ordered in DESC. way
$newPlaylist = $this->Playlists->find('all',['order' => ['Playlists.id' => 'DESC']])->select(['id']);
It's a simple update code in a PHP function through a GET call from the front-end(Not sure if this matters), the code is converting a particular time zone value to unix time stamps -
$oldDate = null;
$newDate = null;
$ctr = 0;
$timeStamp = array();
$query= $this->userDatabaseConnection->stmt_init();
$query->prepare("SELECT Timestamp from Transaction INNER JOIN `Order` ON `Order`.TransactionId = Transaction.TransactionId");
$query->execute();
$query->bind_result($tID); //this holds the current time zone values
while($query->fetch()){
$oldDate = $tID;
array_push($timeStamp, $oldDate);
}
$query->close();
foreach($timeStamp as $row){
$newDate = strtotime($row);
$queryUpdate= $this->userDatabaseConnection->stmt_init();
$queryUpdate->prepare("UPDATE `Order` SET OrderDate=? WHERE TransactionId=?");
error_log("ERROR!",0);
$queryUpdate->bind_param('is', $unixTS, $oldTS);
$unixTS = $newDate;
$oldTS = $row;
$queryUpdate->execute();
$queryUpdate->close();
$ctr++;
}
if($ctr == 88){
return true;
}
else{
return false;
}
}
The $ctr variable is returning the total number of rows that need to be updated - which equals to the correct value and thus returns a true to my front end Angular controller.
I tried echo-ing the $newDate and $row values - they seem to be correct too.
But it just does not update my table. Can someone please help me figure out why? Am I missing something here? The error log does show the message in my Apache log - but I can't seem to figure out what's causing it.
Hello i'm trying to make a post count function based on the codeigniter framework and what i done so far works great looking by my side. The function is complete and everything works fine.
But i have a question here from some experts to tell me that this is the correct ussage of the function and non of the above will harm my page loading. The function is accesed by jQuery get function on every click on the post.
First i'm checking if there is an ip address and if the ip address date inserted is more then 24 hours if its more i'm deleting the current row and then checking again becuase of the previous select its still remembering the last ip address and inserting again with new datime.
And other question should i make cleanjob every week or similar for all ip addreses ?
Here is my code:
function show_count($post_id){
$ip = $this->input->ip_address();
$this->db->select('ip_address,data');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address = $row->ip_address;
$data = $row->data;
}
if(isset($ip_address) && time() >= strtotime($data) + 8640){
$this->db->where('ip_address',$ip);
$this->db->delete('post_views');
}
$this->db->select('ip_address');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address_new = $row->ip_address;
}
if(!isset($ip_address_new) && $ip_address_new == false){
$date = new DateTime('now', new DateTimeZone('Europe/Skopje'));
$this->db->set('views', 'views+ 1', false);
$this->db->where('post_id',$post_id);
$this->db->update('posts');
$data = array(
'ip_address'=>$ip,
'data'=>$date->format("Y-m-d H:i:s")
);
$this->db->insert('post_views',$data);
}
}
Thanks, any suggestions will be appreciate.
Instead of doing lots of queries to increment unique views on your posts, you should use and set cookies and have a fallback method if cookies are not enabled.
$post_id = "???"
if(isset($_COOKIE['read_articles'])) {
//grab the JSON encoded data from the cookie and decode into PHP Array
$read_articles = json_decode($_COOKIE['read_articles'], true);
if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) {
//this post has already been read
} else {
//increment the post view count by 1 using update queries
$read_articles[$post_id] = 1;
//set the cookie again with the new article ID set to 1
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
} else {
//hasn't read an article in 24 hours?
//increment the post view count
$read_articles = Array();
$read_articles[$post_id] = 1;
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}