我是否可以在authorize()函数中为请求创建重定向?我尝试了以下代码,但它不符合重定向请求。任何人都可以对此有所了解吗?
感谢。
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Reserve;
use Cookie;
use Config;
class ClassVoucherCheckoutRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(Reserve $reserve, Cookie $cookie)
{
if((!$cookie->has(Config::get('app.cookie_name'))) || ($reserve->where('cookie_id', $cookie->get(Config::get('app.cookie_name')))->count() == 0))
{
return redirect()->to('butchery-voucher')->withErrors('Your reservation has expired. Places can only be held for up to 30 minutes.');
}
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
];
}
}
答案 0 :(得分:2)
我也有同样的问题,我还没有找到任何解决方案但是我已经通过另一种方式做到了这一点,我知道这不是正确的解决方案,但现在可能有所帮助。
我的问题是:如果数据库中不存在具有相同fb_id
的任何其他用户,我需要注册用户。但我无法检查这种情况,因为middelware在控制器之前执行,它返回fb_id
已经采取的错误。
这是我的UserController
:
public function createUser (UserRequest $request) {
/** here I need to redirect user if the given `fb_id` is already exists
before it was always returning the `fb_id` exists error before executing
the following code, because all input filtered by the `UserRequest` middleware
I have changed the `UserRequest.php` to execute the following code.
**/
$fb_id = Input::get('fb_id');
$user = $this->user->getUserWhereFbIdIn([$fb_id]);
if(sizeof($user) > 0){
return Response::json(['result' => true, 'error' => false, 'message' => 'User exists', 'data' => $user]);
}
// insert user code is here
}
<强> UserRequest.php:强>
public function authorize()
{
return true;
}
public function rules()
{
$fb_id = Input::get('fb_id');
$user = User::where('fb_id', $fb_id)->get()->toArray();
if(sizeof($user) > 0){
return [];
}
return [
'fb_id' => 'required|unique:users',
'username' => 'required|unique:users',
'email' => 'required|unique:users',
'image' => 'required',
'device_id' => 'required',
'status' => 'required',
];
}
答案 1 :(得分:1)
我认为最优雅的解决方案是在您要重定向时使authorize()
返回false
,并覆盖forbiddenResponse()
类上的FormRequest
方法。缺点是你要么必须执行两次条件逻辑,要么设置一个状态变量。
class MyRequest extends FormRequest
{
public function authorize(): bool
{
return Auth::user()->hasNoEmail() ? false : true;
}
public function forbiddenResponse(): Response
{
if Auth::user()->hasNoEmail() return redirect(route('user.should_provide_email'));
return parent::forbiddenResponse();
}
public function rules(): array
{
return [];
}
}
当然,可以认为这样的重定向应该总是在应用于特定路由组的中间件中进行,但是在Request类中可以选择这样做可以很好。