Laravel 5.3 Check if result exist - php

I'm having trouble getting this thing to work. Basically this function is called once I click the delete button of an user config. Users can have multiple configs. What happens is that once I delete a config it looks for another one, if found it sets that as the current profile. If not it should set the config_done back to 0. the first bit works fine but if $firstProfile returns nothing, instead of entering the else it returns me an error..
code:
public function delete(UserConfig $config) {
$user = Auth::user();
$uid = $user->id;
if ($uid == $config->user_id) {
UserConfig::where('id', $config->id)->delete();
$firstProfile = UserConfig::where('user_id', $uid)->first()->id;
if(count($firstProfile)){
$user = User::find($uid);
$user->current_profile = $firstProfile;
$user->save();
return view('/settings');
} else {
$user = User::find($uid);
$user->config_done = 0;
$user->save();
return view('/home');
}
}
}
error:
ErrorException in UserConfigController.php line 100:
Trying to get property of non-object
in UserConfigController.php line 100
at HandleExceptions->handleError('8', 'Trying to get property of non-object', '/Users/jordykoppen/git/beef-monitor/app/Http/Controllers/UserConfigController.php', '100', array('config' => object(UserConfig), 'user' => object(User), 'uid' => '1')) in UserConfigController.php line 100
Keep in mind that I'm very new to Laravel and the whole MVC environment.

Eloquent will return null if no result is found. You're dealing with objects here, so rather than checking the count, you can just do this.
$firstProfile = UserConfig::where('user_id', $uid)->first();
if($firstProfile){
// success
} else {
// not result
}
The $firstProfile variable will either be an instance of UserConfig or it will be null, no need to check the count.

Related

Trying to get property of non-object Notice in custom avatar function for Wordpress

The following custom avatar functions works fine, but I get the following notice
"Trying to get property of non-object in..."
The notice says the problem is on the last part of the function I pasted here - I marked it in the code (look for <-- Notice mentions this line)
Any idea how to fix this? I am stuck...
function test_get_avatar($avatar, $id_or_email, $size, $default, $alt) {
if (!is_numeric($id_or_email)) {
if (is_string($id_or_email)) {
$user = get_user_by('email', $id_or_email);
$id_or_email = $user->ID;
} else if (is_object($id_or_email)) {
if (!empty($id_or_email->ID)) {
$id_or_email = $id_or_email->ID;
}
if (!empty( $id_or_email->comment_author_email)) {
$user = get_user_by('email', $id_or_email->comment_author_email);
$id_or_email = $user->ID; <-- Notice mentions this line
}
}
}
$avatar_id = get_user_meta($id_or_email, 'nicobartes_user_avatar', true);
...
Yes, because get_user_by() can fail and return false. At that point you won't have a wp user object. A test around this code would be:
if ($user = get_user_by('email', $id_or_email->comment_author_email)) {
$id_or_email = $user->ID;
} else {
//Whatever you want to do when this lookup fails
$id_or_email = 0;
}
When you run
$user = get_user_by('email', $id_or_email->comment_author_email);
You should check the value of $user before attempting to get the id on the next line. According to the Wordpress docs, it could potentially be false if no user is found.

Always getting error when cart is empty, Laravel 5

Facing this error:
ErrorException in CartController.php line 35: Trying to get property of non-object
This is the code:
public function index()
{
$this->data['details'] = Cart::content();
$this->data['shipping'] = Shipping::where('region_category_id',session('location'))->where('type',session('type_komoditi'))->first();
$regType = session('regType');
$regId = session('id_wilayah');
$qReg = RegionCategory::find($regId);
if($regType == 'children') {
$this->data['minimalWeight'] = $qReg->minimal_weight;
//$this->data['minimalBuy'] = $qReg->min_buy;
}
$this->data['minimalBuy'] = $qReg->min_buy; //this is line 35
$this->data['regType'] = $regType;
\Session::put('price',Cart::total());
\Session::put('totalPrice',Cart::total());
\Session::put('paycode',0);
return view('client.carts.index',$this->data);
}
when I delete the line 35 the error is gone, but that code is important for using minimal buy filter.
How to resolve this error?
That's error cause $qReg->min_buy return null.
You can fix by return default value like this:
$this->data['minimalBuy'] = $qReg->min_buy ?? 0;
That's mean if is null return 0
It's saying that $qReg is not an object and you are trying to get the value from it using min_buy property.
Try printing the object $qReg using print_r($qReg); and exit the script after that.
print_r($qReg);
exit();
And check whether that object has the property min_buy or not.
Why is $this->data['minimalBuy'] = $qReg->min_buy; after if block ? It's being overwritten even if if($regType == 'children') is false.

Laravel Eloquent Can't Get Attribute When I Use Find

I need to return email of the user like in example:
public function getUserEmailAttribute()
{
$user = User::find($this->used_by);
return $user->email;
}
When I use $this->used_by it's throw me this error:
Trying to get property of non-object (View: /home/mertindervish/Documents/school/app/views/admin/invitation/list.blade.php)
But when I use a string like '2', '3' it's working. Is there any problem with my code? I tried to var_dump $this->used_by and it's return string(1).
It turns out that one invitation didn't have a valid used_by value.
To prevent such an error in the future, add a null check:
public function getUserEmailAttribute()
{
$user = User::find($this->used_by);
if(is_null($user)) return null;
return $user->email;
}

Call to a member function fill() on a non-object

Trying to add information to an empty profile and redirect back.
$user = User::whereUsername($username)->firstOrFail(); // Selects correct user
$input = Input::all(); // a dd($input) at this point confirms input present
$this->profileForm->validate($input); // Passes
$user->profile->fill($input)->save();
return Redirect::route('profile.edit', $user->username);
If $user->profile is null then this gives the error: Call to a member function fill() on a non-object. I tried to remedy this with:
$user = User::whereUsername($username)->firstOrFail(); // Selects correct user
$input = Input::all(); // a dd($input) at this point confirms input present
$this->profileForm->validate($input); // Passes
if ($user->profile == null)
{
$user->profile = new Profile;
}
$user->profile->fill($input)->save();
return Redirect::route('profile.edit', $user->username);
But in this case it is redirected without adding the profile details ($user->profile is still null at this point).
If $user->profile already has information then this problem does not occur and the code works fine.
You can do that like this:
if (count($user->profile))
{
$user->profile->fill($input)->save();
}
else
{
$profile = Profile::create($input);
$user->profile()->save($profile);
}

Codeigniter - Trying to get property of non-object

Please help with the error I'm getting in Codeigniter and grocery crud. Below code is throwing the following message and I'm stuck with it for a few days, I'm a total noob : (
Error:
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/examples.php
Line Number: 70
ps:
Function does what it needs, but the above error shows up.
I appreciate your thoughts on this!
function security() {
$method = $this->uri->segment(3); //tell ci that we are working on url segment 3, e.g. delete, update ....
if ($method == "edit" or $method == 'update_validation' or $method == 'delete') {
$id = $this->uri->segment(4); //work on url segment 4, now pointing at posts table primary key
$this->db->where('posts.user_id', $this->session->userdata('id'));
$result = $this->db->get_where('posts', array('id' => $id), 1)->row();
//this is line: 70 if ($result->id != $id)
{
echo "You don't have access";
exit;
}
else return true;
}
}
You may want to add a value check to the $this->db->get_where('posts', array('id' => $id), 1)->row(); line. It seems like that line may be returning false or something if no row is available, though I can't find the exact return value in the documentation.
$result = this->db->get_where('posts', array('id' => $id), 1)->row();
if (!$result || $result->id != $id) {
echo "You don't have access";
exit;
}

Categories