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(); }
We can update the records using the DB facade with update method. The syntax of update method is as shown in the following table. Run an update statement against the database.
In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.
In eloquent ORM, $fillable attribute is an array containing all those fields of table which can be filled using mass-assignment. Mass assignment refers to sending an array to the model to directly create a new record in Database.
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.
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();
Try doing it like this.
User::where('email', $userEmail)
->update([
'member_type' => $plan
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With