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

15

我正尝试使用Laravel 5.1的表单请求验证机制,以授权请求是否来自所有者。当用户尝试通过show.blade.php更新表格clinics的一部分时,将使用此验证。

到目前为止,我的设置如下:

routes.php:

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

ClinicController.php:

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

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

UpdateClinicAddressFormRequest.php:

public function authorize()

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

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

Show.blade.php

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

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

如果我在授权函数中使用dd($clinicId),它会返回null,所以我认为问题就出在那里!

请问有任何帮助可以解决“禁止访问”的问题吗?非常感谢。

2个回答

33
您遇到了“禁止访问错误”,因为表单请求的authorize()方法返回了false。问题出在这里:$clinicId = $this->route('postUpdateAddress'); 为了在表单请求中访问路由参数值,您可以使用以下代码:$clinicId = \Route::input('id'); //获取{id}的值。 因此,authorize()应该如下所示:
public function authorize()
{
    $clinicId = \Route::input('id'); //or $this->route('id');

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

1
非常感谢您的帮助!这么简单的事情。 - user860511
欢迎。愉快编码。 - Emeka Mbah

4

我在Request中的authorize()方法中添加了这个owner confirmation,使其工作。

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

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