Ben Ben - 4 months ago 46
PHP Question

Laravel 5 form request validation returning forbidden error

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

clinics
through the
show.blade.php
.

My set up so far:

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() !!}



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


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

Answer

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

The issue is this: $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}

so authorize() should look like this:

public function authorize()
{
    $clinicId = \Route::input('id');

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