user860511
user860511

Reputation:

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.

Upvotes: 15

Views: 20794

Answers (2)

Emeka Mbah
Emeka Mbah

Reputation: 17553

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'); //or $this->route('id');

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

Upvotes: 33

Peter Papp
Peter Papp

Reputation: 41

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

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

Upvotes: 4

Related Questions