Laravel | Updating the Logged-In User - save() vs update()

2.8k views Asked by At

I want to update a field of the logged-in user.

In my controller, this works:

Auth::user()->the_field = $theField;
Auth::user()->save();

This doesn't:

Auth::user()->update(['the_field' => $theField]);

I would expect this to work since similar code (updating an order for example) works fine. Something like:

$order->update(['order_status' => OrderStatus::ORDER_COMPLETED]);

So why is it not working? Am I doing something wrong?

2

There are 2 answers

2
anas omush On BEST ANSWER

You have to add fields you want to update in $fillable property User Model when using create or update Method. Based on Laravel Documentation

protected $fillable = [
       
     'the_field'
];
1
Babak Asadzadeh On

Auth::user() contains a model collection of user's information. that's because update method doesn't work on it, update method only works on model instance.

for example look at this code:

//////////////////////////////////////////////////////////////////    
first way
//////////////////////////////////////////////////////////////////
$user = User::where('id',$id)->first();

// if you dd $user here you will get something like this 
User {#4989 ▼
#fillable: array:36 [▶]
  #dates: array:3 [▶]
  #hidden: array:2 [▶]
  #collection: null
  #primaryKey: "_id"
  #parentRelation: null
  #connection: "mongodb"
  #table: null
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:20 [▶]
  #original: array:20 [▶]
  #casts: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: array:2 [▶]
  #touches: []
  +timestamps: true
  #visible: []
  #guarded: array:1 [▶]
  #rememberTokenName: "remember_token"
  -roleClass: null
  -permissionClass: null
}
//and first() method ends other queries because it returns collection not Builder class 

//this doesn't work
$user->update(['the_field' => $theField]);

//but this will work
$user->the_field = $theField;
$user->save();

//////////////////////////////////////////////////////////////////    
second way
//////////////////////////////////////////////////////////////////

$user = User::find($id);

//this will work
$user->update(['the_field' => $theField]);

//and this will work too
$user->the_field = $theField;
$user->save();