问题描述
我正尝试使用以下控制器更新用户配置文件,但问题是如果我仅更新配置文件图片,则会显示上述错误.如何在不更新每个值的情况下更新userProfile:
I was trying to update my userprofile with the following controller but the problem is if i update only profile picture it shows the above error..But if i update every value it update successfully. How do i update the userProfile without updating every value :
public function updateUser(Request $request)
{
$this->validate($request, [
'profile_picture' => 'dimensions:width=400,height=400',
'cover_picture' => 'dimensions:width=800,height=400',
'avatar' => 'dimensions:width=80,height=80',
]);
if (\Auth::check())
{
$user= User::find(\Auth::id());
}
$files= [];
if($request->file('profile_picture')) $files[] = $request->file('profile_picture');
if($request->file('cover_picture')) $files[] = $request->file('cover_picture');
if($request->file('avatar')) $files[] = $request->file('avatar');
foreach($files as $file)
{
if(!empty($file))
{
$filename = time().str_random(20). '.' . $file->getClientOriginalExtension();
$file->move('users/',$filename);
$filenames[]=$filename;
}
}
$user->profile_picture = $filenames[0];
$user->cover_picture = $filenames[1];
$user->avatar = $filenames[2];
$user->save();
return redirect::back()->with('Warning',"Profile Updated Successfully");
}
推荐答案
使用这样的位置数组,我认为这样做不明智,正如您所发现的,如果有人只想更新其头像,该怎么办?我觉得您分配给 $ files []
是多余的,您可以直接处理代码.
I don't think it's wise using a positional array like this, As you've discovered, what if someone only wants to update their avatar. I feel your assignment into $files[]
is redundant and you could go straight into your processing code.
基本上,您当前的实现意味着 $ files
可以具有可变长度,您怎么知道0、1或2等?
Basically your current implementation means $files
can be of a variable length, how do you know which is 0, 1 or 2 etc ?
使用我的方法,代码现在循环遍历每种类型的图片,并通过相同的匹配type属性将其直接分配给 $ user-> $ type
的用户.
With my approach, the code is now looping over each type of picture, and assigns it into the user with $user->$type
directly by the same matching type property.
foreach( array( 'profile_picture', 'cover_picture', 'avatar' ) as $type)
{
if( $request->file( $type ) )
{
$filename = time() . str_random(20) . '.' . $request->file( $type )->getClientOriginalExtension();
$request->file( $type )->move( 'users/', $filename );
$user->$type = $filename;
}
}
如果发现需要将其他$ source映射到$ type变量,则可以使用附加的数组索引来完成此操作...
If you find you need to map a different $source to the $type variable, you could do this with an additional array index...
foreach( array(
'profile_picture' => 'profile_picture',
'cover_picture' => 'cover_picture',
'avatar' => 'avatar'
) as $source => $type)
{
if( $request->file( $source ) )
{
$filename = time() . str_random(20) . '.' . $request->file( $source )->getClientOriginalExtension();
$request->file( $source )->move( 'users/', $filename );
$user->$type = $filename;
}
}
这篇关于(1/1)ErrorException未定义偏移量:1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!