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

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

Related

Why model/variable keeps its value?

I have problem with my code in Laravel Framework. What I am trying to do is sell method inside model. The problem is that $variable keeps its value untill next code execution. How I should make it so it's gonna work like I want to?
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.
Even if you have deleted a record from a database by $this->delete(), $user_item variable still holds a reference to the filled model until the script ends or you destroy the variable.
It seems that you want to return a result of the sell() function. In your case it would be
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->Sell();
I don't know what you are trying to do but below code will solve your issue -
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
$this->ItemData = $this->ItemData->fresh()
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.

Error:Argument 3 passed to App\Http\Controllers\mycontroller::cH() must be an instance of Illuminate\Http\Request, none given

I am getting the error as mentioned above in Question here is my method code
function customHeader($id, $user_id, Request $request){
if ($user_id == Auth::user()->id || Auth::user()->is_admin){
$method = $request->method();
// To show View
if($request->isMethod('GET')){
} // Create
elseif($request->isMethod('POST')){
// Delete
} elseif($request->isMethod('Delete')){
//Delete single
} else{
return redirect()->back();
}
}
Above in function parameters id is required only when user need to Delete records .. i think that error is due that id but i need the id variable. If i remove that $id it works for Create how can i fix that error
Route is as
Route::any('/setting/custom-header/{id?}', 'SettingController#customHeader');
function customHeader(Request $request, $id, $user_id = null){
if ($user_id == Auth::user()->id || Auth::user()->is_admin){
$method = $request->method();
// To show View
if($request->isMethod('GET')){
} // Create
elseif($request->isMethod('POST')){
// Delete
} elseif($request->isMethod('Delete')){
//Delete single
} else{
return redirect()->back();
}
}
change argument order make request as first param and give argument to default value should work.

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.

Undefined index error when trying to echo values, I am using functions outside of the class

Hey guys I have a question and I still consider myself pretty new at coding, so forgive me if I come off foolish.
I am studying in school as of now and we have a project to build a full stack recreation of craigslist. Any who the problem I am having deals with PHP. I have created an account page with text areas. I would like to echo out the user's information on their so the user can see what he put on and update as he likes. Since my navbar is included on every page, I added the code:
if(isset($_SESSION['logged_in_user'])){
var_dump($_SESSION['logged_in_user']);
$user = $_SESSION['logged_in_user'];
var_dump($user);
}
on my account page I figured I can echo it out as
<?= $attributes['first_name']?> within the placeholders. But I keep getting:
Undefined index: first_name
Also when I var_dump($user) I get an protected $attributes array.
In My Auth class is where I first defined $user as such:
public static function attempt($attemptedUsername, $attemptedPassword) {
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
and my findByUserName function is in the user class. the code is:
public static function findByUserName($user_name){
// Get connection to the database
self::dbConnect();
$stmt = self::$dbc->prepare('SELECT * FROM users WHERE user_name = :user_name');
$stmt->bindValue(':user_name', $user_name , PDO::PARAM_STR);
//execute gets its own line, t or false
$stmt->execute();
$result=$stmt->fetch(PDO::FETCH_ASSOC);
// #TODO: Create select statement using prepared statements
// #TODO: Store the result in a variable named $result
// The following code will set the attributes on the calling object based on the result variable's contents
$instance = null;
if ($result) {
$instance = new static($result);
}
return $instance;
}
Your problem seems to be with not being able to access the variable $user outside of the static method attempt() this can be fixed by declaring the variable globally at the beginning of the method attempt() like this:
public static function attempt($attemptedUsername, $attemptedPassword) {
global $user;
$user = User::findByUserName($attemptedUsername);
if ($user == null) {
return false;
}
$validPassword = password_verify($attemptedPassword,$user->password);
if ($validPassword == true) {
$_SESSION['logged_in_user'] = $user;
}
return false;
}
More information can be found on this in the PHP documentation here.

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

Categories