Reputation: 2485
I am trying to update a User on the basis of the email not there id, is there a way of doing this without raw queries.
Currently the error
{"error":{"type":"ErrorException","message":"Creating default object from empty value","file":"C:\wamp\www\celeb-jim\app\controllers\SignupController.php","line":189}}
My Code
public function changeAccountStatus ($plan, $userEmail ){ $UpdateDetails = User::where('email', '=', $userEmail)->first(); $UpdateDetails->member_type = $plan; $UpdateDetails->save(); }
Upvotes: 25
Views: 270417
Reputation: 3725
It is very simple to do. Code are given below :
DB::table('user')->where('email', $userEmail)->update(array('member_type' => $plan));
Upvotes: 7
Reputation: 4780
Try doing it like this.
User::where('email', $userEmail)
->update([
'member_type' => $plan
]);
Upvotes: 24
Reputation: 91
$update = \DB::table('student') ->where('id', $data['id']) ->limit(1) ->update( [ 'name' => $data['name'], 'address' => $data['address'], 'email' => $data['email'], 'contactno' => $data['contactno'] ]);
Upvotes: 9
Reputation: 10794
You could use the Laravel query builder, but this is not the best way to do it.
Check Wader's answer below for the Eloquent way - which is better as it allows you to check that there is actually a user that matches the email address, and handle the error if there isn't.
DB::table('users')
->where('email', $userEmail) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('member_type' => $plan)); // update the record in the DB.
If you have multiple fields to update you can simply add more values to that array at the end.
Upvotes: 39
Reputation: 9883
This error would suggest that User::where('email', '=', $userEmail)->first()
is returning null, rather than a problem with updating your model.
Check that you actually have a User before attempting to change properties on it, or use the firstOrFail()
method.
$UpdateDetails = User::where('email', $userEmail)->first();
if (is_null($UpdateDetails)) {
return false;
}
or using the firstOrFail()
method, theres no need to check if the user is null because this throws an exception (ModelNotFoundException
) when a model is not found, which you can catch using App::error()
http://laravel.com/docs/4.2/errors#handling-errors
$UpdateDetails = User::where('email', $userEmail)->firstOrFail();
Upvotes: 15