Laravel 5.1 redirect() - > back()无效

时间:2015-08-12 15:23:19

标签: php laravel redirect laravel-5.1

我正在为文件上传构建以下存储库。我需要检查文件大小,如果验证失败,重定向回到有错误的表单。但是当checkSize失败时,重定向将不会发生。有什么问题?

<?php
namespace app\Repositories;

class UploadFileRepository
{
    public $fileNames=[];
    protected $maxSize=2097152;
    public function upload($files){
        foreach ($files as $file){
            if(!empty($file)){
                $filename=$file->getClientOriginalName();
                $this->checkSize($file);
                $this->fileNames[]=$filename;
                $file->move(base_path().'/public/uploads/', $filename);
            }
        }
    }
    protected function checkSize($file){
        $fileSize=$file->getClientSize();
//        dd($fileSize);
        $filename=$file->getClientOriginalName();
        if ($fileSize == 0) {
          return  redirect()->back()->withInput()->withErrors([ $filename. ' is empty.']);
        } elseif ($fileSize > $this->maxSize) {
            return redirect()->back()->withInput()->withErrors([ $filename. ' is too large.']);
        } else {
            return true;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您需要在upload函数(或您的路由正在调用的任何函数)中返回响应。 在您的代码中,checkSize会在出现错误时返回响应,但upload不会返回错误,因此它会丢失。

以下是您可以做的事情:

class UploadFileRepository
{
    public $fileNames=[];
    protected $maxSize=2097152;

    public function upload($files){
        foreach ($files as $file){
            if(!empty($file)){
                $filename=$file->getClientOriginalName();

                $error = '';
                if (!$this->checkSize($file, $error))
                    return redirect()->back()->withInput()->withErrors([ $error ]);

                $this->fileNames[]=$filename;
                $file->move(base_path().'/public/uploads/', $filename);
            }
        }
    }

    protected function checkSize($file, &$error){
        $fileSize=$file->getClientSize();
        $filename=$file->getClientOriginalName();

        if ($fileSize == 0) {
            $error = $filename . ' is empty.';
            return false;
        } elseif ($fileSize > $this->maxSize) {
            $error = $filename . ' is too large.';
            return false;
        } else
            return true;
    }
}

答案 1 :(得分:1)

您可以尝试:返回() - &gt; with(&#39;错误&#39;,&#39;错误消息&#39;);