未定义变量:request

8
当我尝试上传文件时,出现错误:
未定义变量: 请求
这是我使用它的地方: UploadController:
if($request->hasFile('file')){
        $file = $request ->file('file');
        $fileName = $file->getClientOriginalName();
        $destinationPath = config('app.fileDesinationPath').'/'.$fileName;
        $uploads = Storage::put($destinationPath,file_get_contents($file->getRealPath()));

    }
    return redirect()->to('/upload');

这里出了什么问题?

5个回答

24

在你的函数中添加Request $request参数。例如:

public function yourFunction(Request $request)
{
    if($request->hasFile('file')){
        $file = $request ->file('file');
        $fileName = $file->getClientOriginalName();
        $destinationPath = config('app.fileDesinationPath').'/'.$fileName;
        $uploads = Storage::put($destinationPath,file_get_contents($file->getRealPath()));

    }
    return redirect()->to('/upload');
}
请仔细阅读文档:http://laravel.com/docs 此外,您还可以在这里观看 Laravel 教程:http://laracasts.com

谢谢,我已经这样做了。但是现在它显示:找不到类'App\Http\Controllers\Storage'。 - Rock
1
我认为使用request()辅助函数,正如@Amit Gupta所述,是更合适的方式,特别是当一个人在控制器之外访问请求时。 - Mugoma J. Okomba
运行正常。谢谢。 - moreirapontocom

7
您也可以使用 request() 助手函数,例如:
if(request()->hasFile('file')) {
    ...
}

请求功能返回当前请求实例。

3
如果想从 Blade 访问请求,这是正确的答案。 - Mugoma J. Okomba
我同意,这是最好的答案。你的函数不需要传递额外的参数。 - GTS Joe

2
使用Request::hasFile代替$request。例如:
if(Request::hasFile('file')){
    $file = Request::file('file');
    $fileName = $file->getClientOriginalName();
    $destinationPath = config('app.fileDesinationPath').'/'.$fileName;
    $uploads = Storage::put($destinationPath,file_get_contents($file->getRealPath()));

}
return redirect()->to('/upload'); `

1
要访问$request变量,您需要将其添加到方法参数中。
public function myFunction(Request $request)
{ 
   // access $request here
}

为了使这个工作,你需要添加。
use Illuminate\Http\Request;

如果您想在请求中进行验证和授权,可以创建自己的请求,而不是直接使用Illuminate的请求类,只需使用即可。
php artisan make:request MyRequest

你会找到授权方法和返回验证规则的部分。

谢谢,我已经做了那个。但是现在它显示:找不到类 'App\Http\Controllers\Storage'。 - Rock

0

显然你的方法中没有注入$request(我想,你只发布了部分方法)。检查一下,如果需要,请将其作为参数添加。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接