这是我为所有控制器使用的一般功能所做的HelperController
namespace App\Http\Controllers;
use Session;
use Redirect;
use App\Http\Requests;
use Illuminate\Http\Request;
class HelperController extends Controller
{
public function UploadImage($UploadImage,$folder)
{
if($UploadImage->isValid() && $UploadImage->getMaxFilesize()>=$UploadImage->getSize())
{
if($UploadImage->guessExtension()=='jpeg' || $UploadImage->guessExtension()=='jpg' || $UploadImage->guessExtension()=='gif' || $UploadImage->guessExtension()=='png')
{
$destinationPath = public_path().'/assets/images/'.$folder.'/';
$uploadedFilename = time().'_'.$UploadImage->getClientOriginalName();
$UploadImage->move($destinationPath,$uploadedFilename);
return $uploadedFilename;
} else {
return Redirect::to('/profile')->with('errorMessage','Extension Issue');
// or
// return back()->with('errorMessage','Extension Issue');
// or
// return "extension";
}
} else {
return Redirect::to('/profile')->with('errorMessage','Size Issue');
// or
// return back()->with('errorMessage','Size Issue');
// or
// return "size";
}
}
public function beautifyRole($role)
{
return ucwords(str_replace('_',' ',$role));
}
}
这是Profile Controller我使用HelperController的UploadImage函数上传图片
namespace App\Http\Controllers;
use Auth;
use App\User;
use App\Http\Requests;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function UpdateProfile(Request $request)
{
$User = User::where('id',Auth::User()->id)->first();
$User->name = $request->Input('name');
$User->email = $request->Input('email');
$User->password = bcrypt($request->Input('password'));
// Check if New Avatar if Uploaded
if($request->avatar!=null){
$HelpUpload = new HelperController;
$avatar = $HelpUpload->UploadImage($request->avatar,'users');
/*
if($avatar=='size'){
return back()->with('errorMessage','File Size Issue');
} elseif($avatar=='extension'){
return back()->with('errorMessage','File Extension Issue');
} else {
$User->avatar = $avatar;
}
*/
}
$User->save();
return Redirect('/profile')->with('successMessage','Profile Updated Successfully');
}
}
但是如果不满足尺寸或扩展条件则存在问题,我希望页面重定向到上一页或直接重定向到配置文件页面。相反,它会返回到UploadProfile函数并始终显示" Profile已成功更新"即使发生任何错误也要留言。
我想删除UpdateProfile函数上的控件结构。它在我返回错误消息然后在更新配置文件功能上检查它时有效。
我们可以直接从HelperController中的UploadImage函数重定向到配置文件页面,而无需返回到正常的函数。
答案 0 :(得分:0)
如果您的图片上传功能不像
那样,您可以使用redirect()->back()
方法和错误消息
return redirect()->back()->withErrors("Your error message");