这是从控制器类方法包装一些代码的好习惯,因为它太长并将该代码放在控制器类下面的另一个自定义函数中。
这是控制器方法:
public function store(UploadRequest $request)
{
//Provjera duljine imena slike (max 20 znakova)
if(!is_valid_name($request->file('file'))) {
return redirect()->back()->withErrors(['File name can\'t be longer than 20 characters.']);
}
$user = Auth::user();
$time = time();
$image = $request->file('file');
//Dodaj trenutno vrijeme prije imena slike kako bi se slika mogla identificirati
$image_name = $time . $image->getClientOriginalName();
//Ako je slika png spremi ju bez konverzije
if($image->getClientOriginalExtension() == "png")
{
Storage::put('public/images/'.$user->id.'/png/'.$image_name, file_get_contents($image));
save_image_to_database($image, $user, $time);
}
Save_image_to_database() 是我写在控制器类下面的自定义函数:
function save_image_to_database($image, $user, $time){
$db_image = new Image();
if($image->extension() == 'png')
{
$db_image->path = $time . $image->getClientOriginalName();
$db_image->png_size = $image->getClientOriginalSize();
}
else
{
$path = $time . pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME).'.png';
$png_size = Storage::size('/public/images/'.$user->id.'/png/'.$path);
$db_image->path = $path;
$db_image->png_size = $png_size;
}
$db_image->user_id = $user->id;
$db_image->extension = $image->extension();
$db_image->size = $image->getClientSize();
$db_image->save();
return redirect('/images');
}
问题是自定义函数中的 redirect() 方法不起作用,它重定向到空白窗口,但浏览器“localhost:8000/images”中的路径是正确的。当我手动刷新站点时,它可以工作并返回视图。如果我将该 redirect() 方法从自定义函数移动到控制器 store() ,那么它运行良好。