簡體   English   中英

Laravel | 更新登錄用戶 - save() vs update()

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

我想更新登錄用戶的字段。

在我的 controller 中,這是有效的:

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

這不會:

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

我希望這可以正常工作,因為類似的代碼(例如更新訂單)可以正常工作。 就像是:

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

那么為什么它不起作用呢? 難道我做錯了什么?

使用 create 或 update 方法時,您必須在 $fillable 屬性 User Model 中添加要更新的字段。 基於Laravel 文檔

protected $fillable = [
       
     'the_field'
];

Auth::user()包含用戶信息的 model 集合。 那是因為更新方法不適用於它,更新方法僅適用於 model 實例。

例如看看這段代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM