Laravel Eloquent Can't Get Attribute When I Use Find - php

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;
}

Related

Property [vegan] does not exist on this collection instance. Laravel

I'm trying to show a title based on whether a specific column in my table is 1 or 0. In my Controller I have (edited out some irrelevant code):
public function show(Company $id){
$vegan = Company::find($id);
$vegetarian = Company::find($id);
return view('allProducts')->with([
'vegan' => $vegan,
'vegetarian' => $vegetarian,
]);
}
and in my view:
#if($vegan->vegan == 1)
<h3 class="text-center">Vegan</h3>
#endif
However I get error message
ErrorException (E_ERROR)
Property [vegan] does not exist on this collection instance. (View: C:\xampp\htdocs\EdenBeauty\resources\views\allProducts.blade.php)
Ive tried the following but I get errors every time:
#if($vegan[0]->vegan == 1)
This gives undefined offset errors
The problem is you're missing first() after your queries:
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();
In this line, you're injecting a Company into your show method via URL parameter:
public function show(Company $id){ ... }
At that point, $id is either a Company instance or null. Calling $vegan = Company::find($id) doesn't make any sense, and I'm actually surprised you don't get an error at that point in the code.
Also, if you're using injection, name the variable correctly Company $company to avoid confusion, and reference later:
public function show(Company $company){
$vegan = $company;
$vegetarian = $company;
// Or `$vegan = Company::find($company->id);`
// (This is redundant, but demonstrates the syntax)
return view("...")->with(...);
}
Alternatively, remove injection and query:
public function show($id){
$vegan = Company::find($id); // Note can use use `firstOrFail()`, etc.
$vegetarian = Company::find($id);
...
}
Either way, find() does not return a Collection, so $vegan->vegan would not return "Property [vegan] does not exist on this collection instance.", but something about your usage is treating it that way.

why i m null getting value in laravel

here is my controller i don't know why i have null value i check using dd($user)
public function success1(Request $request)
{
$phonetoken = $request->input('phonetoken');
$user =User::where('phonetoken', $phonetoken)->first();
dd($user);
if(!is_null($user)){
$user->phoneconfirmed = 1;
$user->phonetoken = " ";
$user->save();
return redirect('sellerdashboard');
}
return redirect()->back();
}
why i m not getting value in $user always getting null
Thats probably because your eloquent cannot find the result.
Use dd($phonetoken) just to be sure the variable is being passed properly.
Also check phonetoken is in your user model.
Othet than this your code seems to be correct.

Laravel 5.3 Check if result exist

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.

Trying to get property of non-object with PHP

I have a strange issue; my code is working on my localhost, but when I try to use it online. It's showing an error in the return line:
Trying to get property of non-object
Here is the code:
public static function displayContenuAsString ($id,$class="traduction survol_video",$div="div") {
return "<$div id=\"contenu_$id\" class=\"$class\"></$div>".Contenu::model()->findByPk($id)->valeur;
}
No issues in the code Contenu::model()->findByPk($id)->valeur; Just check for the row in database with primary key.
According to documentation findByPk return the record found or Null if none is found. So you need to add check before using model values in this way:
public static function displayContenuAsString ($id,$class="traduction survol_video",$div="div") {
$contenu = Contenu::model()->findByPk($id);
$valeur = $contenu !== null ? $contenu->valeur : 'Empty';
return "<$div id=\"contenu_$id\" class=\"$class\"></$div>".$valeur;
}

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);
}

Categories