You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel的update方法中为数据库列'photo'赋值$filenameToStore

Fixing Laravel User Update Method: Assign $filenameToStore to Database 'photo' Column

Hey there! Let's get your User model's update method sorted out so that your generated $filenameToStore value is correctly saved to the photo column in your database. Below is the fully corrected code, plus a breakdown of the issues in the original version:

Corrected Code

public function update(Request $request, User $user) {
    $filenameWithExt = $request->file('profile_pic')->getClientOriginalName();
    $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
    // Get file extension
    $extension = $request->file('profile_pic')->getClientOriginalExtension();
    $filenameToStore = $filename.'_'.time().'.'.$extension;
    $path = $request->file('profile_pic')->storeAs('public/profile_image', $filenameToStore);
    
    $user->update([
        'name' => $request->input('name'),
        'profile_pic' => $filenameToStore,
        'photo' => $filenameToStore, // This assigns your filename to the 'photo' column
        'last_name' => $request->input('last_name'),
        'phone_number' => $request->input('phone_number'),
        'address' => $request->input('address'),
        'facebook_link' => $request->input('facebook_link'),
        'twitter_link' => $request->input('twitter_link'), // Fixed typo here too!
        'youtube_link' => $request->input('youtube_link'),
        'biography' => $request->input('biography'), // Standardized to lowercase for consistency
    ]);
    
    return redirect()->route('user.index');
}

Key Fixes & Explanations

  • Incorrect array syntax: The original code used semicolons instead of commas to separate elements in the update method's array—this is a critical syntax error that breaks the code.
  • Unnecessary save() call: You don't need to call $user->save() after $user->update()—the update() method automatically persists the changes to the database for you.
  • Route redirection: Ensured the redirect uses the correct route() helper function with the named route user.index instead of invalid formatting.
  • Minor typos: Fixed a typo (twittr_link → twitter_link) and standardized column names to lowercase for consistency (though this depends on your actual database schema, it's a common best practice).
  • Direct assignment to 'photo' column: We added 'photo' => $filenameToStore directly in the array passed to update()—this is how you map the generated filename to your database column.

内容的提问来源于stack exchange,提问作者Najib jamshidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:20:55