在我的应用程序中,用户可以上传其个人资料照片的图像.如何更新用户照片和删除以前上传的照片?这是我到目前为止在上传控制器中所拥有的:
照片模型
class Photos extends Eloquent { protected $table = 'photos'; protected $fillable = array('user_id', 'location'); public function user (){ return $this->belongsTo('User'); } }
用户模型
public function photos() { return $this->hasOne('photos'); }
上传控制器
class UploadController extends \BaseController { public function postUpload (){ $id = Auth::user()->id; $input = Input::all(); $rules = array( 'photo' => 'required|image|max:500' ); $validator = Validator::make($input, $rules); if($validator->fails()){ return Redirect::to('user/profile/'.$id.'/edit')->withErrors($validator); } $extension = Input::file('photo')->getClientOriginalExtension(); $directory = public_path('/var/chroot/home/content/59/11581559/html/beta') . '/uploads/'.sha1($id); $filename = sha1($id.time()).".{$extension}"; $upload_success = Input::file('photo')->move($directory, $filename); Image::make(Input::file('photo')->getRealPath())->resize(300, 200)->save('foo.jpg'); if($upload_success){ $photo = new Photos(array( 'location' => URL::to('/uploads/'.sha1($id).'/'.$filename) )); $photo->user_id = $id; $photo->save(); Session::flash('success_photo', 'You have Successfully uploaded your profile photo!'); return Redirect::to('user/profile/'.$id.'/edit'); } else{ Session::flash('status_error', 'An Error has occurred while uploading your photo. Please try again!'); } return Redirect::to('user/profile/'.$id.'/edit'); } }
视图
@if(Session::has('status_error'))@endif Upload a Photo {{ implode('', $errors->all(':status_error ')) }}@if($user->photos) @endif
James Binfor.. 5
让我们谈谈你在做什么,从那里开始工作.
上传照片 - 在控制器中,您正在上传照片. - 如果上传成功,您将在服务器上存储照片的位置以及照片所属的用户的ID.
更新照片 - 在控制器中,您正在上传照片. - 如果上传成功,您将:
获取当前文件在数据库中的位置.
$this->photo->where('user_id' , '=' , $the_user_id_in_question)
->get(array('location'));
使用delete()
FileSystem类中的函数删除该位置的文件(可在此处找到:https://github.com/laravel/framework/blob/master/src/Illuminate/Filesystem/Filesystem.php)
使用新的照片位置更新用户的照片位置:
$this->photo->where('user_id' , '=' , $the_user_id_in_question)
->update('location' => $the_new_upload_location);
我希望这就是你要找的东西.干杯!
让我们谈谈你在做什么,从那里开始工作.
上传照片 - 在控制器中,您正在上传照片. - 如果上传成功,您将在服务器上存储照片的位置以及照片所属的用户的ID.
更新照片 - 在控制器中,您正在上传照片. - 如果上传成功,您将:
获取当前文件在数据库中的位置.
$this->photo->where('user_id' , '=' , $the_user_id_in_question)
->get(array('location'));
使用delete()
FileSystem类中的函数删除该位置的文件(可在此处找到:https://github.com/laravel/framework/blob/master/src/Illuminate/Filesystem/Filesystem.php)
使用新的照片位置更新用户的照片位置:
$this->photo->where('user_id' , '=' , $the_user_id_in_question)
->update('location' => $the_new_upload_location);
我希望这就是你要找的东西.干杯!