Laravel DB first() "Trying to get property of non-object" - php

I run a query using Laravel's DB first() which returns an object, when I check using dd() or vardump(). But when I try to print the value using echo ($promotion->pp_name); it gives error, but same property shows while dd($promotion->pp_name);
<?php dd($promotion->pp_name); ?> prints "urgent"
<?php echo ($promotion->pp_name); ?> but it gives "Trying to get property of non-object"
Full object dump results: <?php dd($promotion); ?>
{#196 ▼
+"ppo_id": 23
+"ppo_prj_id": 68
+"ppo_pp_id": 4
+"ppo_updated_date": "2014-05-20"
+"ppo_status": 1
+"pp_id": 4
+"pp_name": "urgent"
+"pp_dispText": "I want my project to be marked as an urgent project"
+"pp_amount": "5.00"
+"pp_updated_date": "2013-08-09"
+"pp_status": 1
}
and the function that return this object.
function getProjectPromotion($value='')
{
$project_id = $value;
$promotion = DB::table('project_promotion_option')
->join('project_promotion', 'project_promotion_option.ppo_pp_id', '=', 'project_promotion.pp_id')
->where('ppo_prj_id', '=' , $project_id )
->first();
return $promotion;
}

Are you calling this method in a loop? When you do a dd(), the script stops with the right result after the first loop run and all is good. But when you do echo in a loop, it continues and my guess is that at some point you pass some corrupted data that breaks the method.
We would need to see the code excerpt where you are calling the mentioned method to verify this hunch.

As Tadas Paplauskas suggest because the function call the query run in foreach each loop and in some iteration DB::first() method return null so echo gets error. i solved this by checking first if the value is set.
<?php if (isset($promotion->pp_name)) {
echo $promotion->pp_name;
} ?>

Related

how to update first row on button click

i want to update a first record status into '2' based on button click.
Here is my code :
public function repay(Request $request,$loanid){
$obj = DB::table('schdls')
->where('schdls.loanid','=',$loanid)
->where('schdls.status','=',1)->first();
$obj->status='2';
$obj->save();
return redirect('/home')->with('message','updated');
}
But it says Call to undefined method stdClass::save() error,
What am i missing?
Check if $obj is null before assigning value on it.
Use dd/dump/var_dump function to check the value and the type of $obj after getting record from database.
Try using update(['status' => '2']); instead of save()
DB::table('schdls')
->where('status','=',1)->update(['status' => 2]);

Trying to get property 'times' of non-object

This is a strange one (for me at least), I'm trying to pass an object to a function like so:
272. $runs[$key]['position'] = getTimePosition($run->times,$user['id']);
273. dd($run->times);
When I do it I get the error
message: "Trying to get property 'times' of non-object", exception: "ErrorException",…}
exception: "ErrorException"
file: "C:\Users\Test\PhpstormProjects\test\app\Helpers\Helper.php"
line: 272
message: "Trying to get property 'times' of non-object"
However, if I dump $run->times I get what seems to be correct, an Eloquent object with "times" as shown below...
What am I missing here? It's been bugging me for an hour
As I guess your result set return multiple rows so that you need to iterate them by using the loop or you can get the result by using.
$run[0]->time
If you want to get a single row from DB you should use it.
$run = DB::table('tableName')->where('condition')->first();
$run->time
It will work.
Your attribute name is $run->time, not $run->times
$runs[$key]['position'] = getTimePosition($run->time,$user['id']);
Try this one
if($run) {
$runs[$key]['position'] = getTimePosition($run->times,$user['id']);
}

How to solve Message: Trying to get property of non-object error in Codeigniter?

I'm very fresher in CodeIgniter and practicing. I'm now developing a simple Codeigniter application just for practicing. I've Banks and its branches in the database. I just want to show branches with its bank name. Branches are showing but in the controller while getting banks, this error is showing. I tried these in SO links, but nothing found works.
"A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object"
in Line Number: 85 and 91
This is my controller
function ShowBranchList() {
$branch_list = $this->FD_Model->get_all_branches();
$get_bank = $this->FD_Model->get_bank_by_branch($branch_list->bankid); //This is Line Number 85
if($branch_list ){
$data = array(
'pagetitle' => 'Branch List View',
'branch_list_data' => $branch_list,
'br_bank' => $get_bank['bank_name'],//This is Line Number 93
);
}
Model
/*function for getting all branches*/
function get_all_branches() {
$this->db->order_by( $this->brid, $this->order );
return $this->db->get( $this->brtable )->result();
}
/*function for getting banks by branches*/
function get_bank_by_branch( $id ) {
$this->db->where( $this->bid, $id);
return $this->db->get( $this->banktable )->row();
}
And finally, this is my View
foreach ($branch_list_data as $branch_list)
{
<?php echo $branch_list->brname ?>
<?php echo $br_bank; ?>
}
Anyone know the issue?
Update
When I'm tring to view the query
echo $this->db->last_query();
Result
SELECT * FROM tbl_bankmaster WHERE bid IS NULL
The value $branch_list->bankid is null.When I'm hardcoding some values the view page is showing without any error.
do like this
$get_bank = $this->FD_Model->get_bank_by_branch($branch_list[0]->bankid);
AND
'br_bank' => $get_bank[0]->bank_name # this will work maybe
or
'br_bank' => $get_bank[0]['bank_name']
Its 0 indexed array so you need to add the key to access the child's
Change your data in view like this
foreach ($branch_list_data as $branch_list)
{
echo $branch_list['brname']; //change your data like this
echo $br_bank;
}
I finally make it happen with the help of Abdulla Nilam's answer. I just passed the value in array like
'br_bank' => $get_bank->bank_name
Now the view is working.
get_bank_by_branch($branch_list->bankid); This method returning only object.
$get_bank this variable you're accessing by an array, but it's an object.

Laravel cannot echo softdeletes field error Carbon Data Missing

I wanna check if the data has been deletes. So i use eloquent like:
$check = ModelName::withTrashed()->where("id","=",$id)
->select("id","deleted_at","other_field")
->get();
foreach ($check as $rw) {
echo $rw->id; // it print the id
echo $rw->other_field; //also print the field value
echo $rw->deleted_at; // Error:
//InvalidArgumentException in Carbon.php line 425:
//Data missing
//at Carbon::createFromFormat('Y-m-d H:i:s.000', '2016-09-19 07:06:56') in Model.php line 2955
}
Then i try to dump to see the value:
dd($check);
The result of deleted_at echo it value like:
#attributes: array:3 [▼
"id" => 1
"deleted_at" => "2016-09-19 07:06:56"
EDIT:
In the error message, date format used by Carbon seems to be a bit off. Try to specify it in your model manually:
protected $dateFormat = 'Y-m-d H:i:s';
I'm leaving the first part of the answer because that might also help someone who stumbles on this topic through search.
dd() stops after the first value, which is soft-deleted in your case, so you simply stop execution before the error. If you remove dd, the loop continues until it breaks. So if you wanna check the all the data up until the error, use print_r instead of dd(), so that output would not stop the script.
Now about your exception. The problem is when Carbon encouters a field that is NULL - a record that's not deleted. It tries to parse null into a date and obviously fails.
Your approach should be changed - you could check if the record is soft deleted before trying to access it's deleted_at timestamp:
$check = ModelName::withTrashed()->where("id","=",$id)
->select("id","deleted_at","other_field")
->get();
foreach ($check as $rw) {
echo $rw->id; // it print the id
echo $rw->other_field; //also print the field value
if ($rw->trashed())
echo $rw->deleted_at;
}
Another, less elegant solution would be to remove deleted_at from $dates array in model and stop the automatic parsing. Then you would write a custom accessor in your model:
public function getDeletedAtAttribute($value)
{
return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value) : NULL;
}
I would recommend the first approach.

Zend-Framework related

I got two zend forms which belongs to one table in the database, broke it up in order to make sure the user does not find it lazy to finish it but I have a problem with my code in my model. I keep getting this error even though I tried numerous solutions.
Fatal error: Call to a member function save() on a non-object
public function smmedetailssmmedetails($companyname, $companytradingname)
{
$data = array(
'companyname' => $companyname,
'companytradingname' => $companytradingname,
);
return $this->insert($data);
}
public function smmesdetails2smmedetails($smmeid, $numberemployees, $ownership)
{
$row = $this->find($smmeid)->current();
$row->numberemployees = $numberemployees;
$row->ownership = $ownership;
return $row->save(); //problem lies on this line
}
Tried using the following codes/methods
$this ->row->save();
$row->save();
$this ->row->save();
return $this -> row->save();
According to the error you're getting, none of the method invocations you are trying will work.
You should first check what
$this->find($smmeid)->current();
returns using either a debugger, var_dump or print_r.
In your case, it seems that either null or something that is not an object is returned.
This means, that $row is not an object (should be), but probably is null. This means that find() method didn't get any result from database.
You should check $smmeid value and check if a such a row exists in the database.
Use var_dump function to check any variable in any line. This is how you can debug your problem.
Hey guys I got it using this method below, I marked codeblur answer because it was close thanks for the print_r information:
Example #1 print_r() example
<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>
return ($row);//correct answer

Categories