[php] Laravel Update Query

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

This question is related to php laravel

The answer is


It is very simple to do. Code are given below :

 DB::table('user')->where('email', $userEmail)->update(array('member_type' => $plan));  

Try doing it like this.

User::where('email', $userEmail)
       ->update([
           'member_type' => $plan
        ]);

$update = \DB::table('student') ->where('id', $data['id']) ->limit(1) ->update( [ 'name' => $data['name'], 'address' => $data['address'], 'email' => $data['email'], 'contactno' => $data['contactno'] ]); 

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.