Laravel调用其他函数后无法返回视图,页面空白问题求助
问题描述
我编写了如下Laravel函数:
public function addNewPhotoRequest($uuid) { $photos = DB::table('photos')->where('uuid', '=', request('qr_code'))->get(); $new_photo_request = new Photos; $new_photo_request->uuid = $uuid; $new_photo_request->save(); $this->submitPhotoRequest($new_photo_request->photo_id); }
执行$this->submitPhotoRequest语句后,函数无法返回视图,也无法使用Return Redirect XXX进行重定向。但如果将返回视图或重定向的语句放在addNewPhotoRequest函数内则可以正常工作,说明视图和路由本身没有问题。目前仅返回空白页面且无报错信息,我可以在submitPhotoRequest函数中执行DD("test"),证明该函数能被正常调用且可运行。
对应的submitPhotoRequest函数:
/** * Submit the API code if it matches a valid code within the database. * This will allow the user to upload a photo and associate it with a database record. * * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function submitPhotoRequest($photo_id) { return view('upload_photo', ['api_code' => $photo_id]); }
请问这是什么原因?
解决方案
问题出在调用submitPhotoRequest的方式上:你只是调用了这个方法,但没有把它返回的视图实例传递给Laravel的响应处理链。
Laravel的控制器方法需要返回一个响应实例(比如视图、重定向响应)才能正确输出内容。submitPhotoRequest确实返回了视图,但addNewPhotoRequest没有把这个返回值继续返回出去,相当于这个视图实例被丢弃了,最终控制器没有返回任何响应,所以页面显示空白。
修改addNewPhotoRequest的最后一行,加上return即可:
return $this->submitPhotoRequest($new_photo_request->photo_id);
同理,如果submitPhotoRequest返回的是重定向响应,也要确保调用时用return传递这个响应,这样Laravel才能正确处理跳转。
内容的提问来源于stack exchange,提问作者masterg174
相关产品推荐
相关产品推荐

