Laravel 5 表单请求验证返回禁止错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30878105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:47:35  来源:igfitidea点击:

Laravel 5 form request validation returning forbidden error

phpvalidationlaravellaravel-4laravel-5

提问by Emeka Mbah

I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinicsthrough the show.blade.php.

我正在尝试使用 Laravel 5.1 的表单请求验证来授权请求​​是否来自所有者。当用户尝试clinics通过show.blade.php.

My set up so far:

到目前为止我的设置:

routes.php:

路线.php:

Route::post('clinic/{id}', 
    array('as' => 'postUpdateAddress', 'uses' => 'ClinicController@postUpdateAddress'));

ClinicController.php:

诊所控制器.php:

public function postUpdateAddress($id, 
        \App\Http\Requests\UpdateClinicAddressFormRequest $request)
    {
        $clinic             = Clinic::find($id);
        $clinic->save();

        return Redirect::route('clinic.index');
    }

UpdateClinicAddressFormRequest.php:

UpdateClinicAddressFormRequest.php:

public function authorize()

    {
        $clinicId = $this->route('postUpdateAddress');

        return Clinic::where('id', $clinicId)
        ->where('user_id', Auth::id())
        ->exists();
    }

Show.blade.php

显示.blade.php

{!! Form::open(array('route' => array('postUpdateAddress', $clinic->id), 'role'=>'form')) !!}

{!! Form::close() !!}

If I dd($clinicId)within the authorize function, it returns null, so I think that's where the problem lies!

如果我dd($clinicId)在授权函数中,它返回null,所以我认为这就是问题所在!

Any help why on submit it's saying 'forbidden' would be hugely appreciated.

任何帮助为什么在提交时说“禁止”将不胜感激。

回答by Emeka Mbah

You are getting Forbidden Errorbecause authorize()method of form request is returning false:

您收到Forbidden Error因为authorize()表单请求方法返回false

The issue is this: $clinicId = $this->route('postUpdateAddress');

问题是这样的: $clinicId = $this->route('postUpdateAddress');

To access a route parameter value in Form Requests you could do this:

要访问表单请求中的路由参数值,您可以执行以下操作:

$clinicId = \Route::input('id'); //to get the value of {id}

$clinicId = \Route::input('id'); //to get the value of {id}

so authorize()should look like this:

所以authorize()应该是这样的:

public function authorize()
{
    $clinicId = \Route::input('id'); //or $this->route('id');

    return Clinic::where('id', $clinicId)
    ->where('user_id', Auth::id())
    ->exists();
}

回答by Peter Papp

I add this owner confirmation to authorize() method in Request and work

我将此所有者确认添加到 Request 中的 authorize() 方法并工作

public function authorize()
{
    return \Auth::check();
}