如何在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
updatemethod'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()—theupdate()method automatically persists the changes to the database for you. - Route redirection: Ensured the redirect uses the correct
route()helper function with the named routeuser.indexinstead 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' => $filenameToStoredirectly in the array passed toupdate()—this is how you map the generated filename to your database column.
内容的提问来源于stack exchange,提问作者Najib jamshidi
相关产品推荐
相关产品推荐

