Leena Patel
Leena Patel

Reputation: 2453

Laravel Prevent Form from Re submitting

I have a form of Adding Album in database

 {!! Form::open(['method' => 'POST', 'route' => ['admin.album.store'], 'enctype' => 'multipart/form-data', 'id' => 'CreateAlbumForm']) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">

// other fields

{!! Form::submit(trans('global.app_save'), ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}

It is working perfectly.

What i need is to prevent user from clicking submit button multiple times. which i know is possible with jquery ( disabling submit button on click).

But i want to make it using csrf protection(Server side) when user does not have javascript enabled.

After a lot of search i found below solution :

What i have tried

Adding Below function in VerifyCsrfToken.php

protected function tokensMatch($request)
{
    $token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');

    if (!$token && $header = $request->header('X-XSRF-TOKEN')) {
        $token = $this->encrypter->decrypt($header);
    }

    $tokensMatch = ($request->session()->token() == $token) ? TRUE : FALSE;

    if($tokensMatch) $request->session()->regenerateToken();

    return $tokensMatch;
}

And adding _token inside $dontFlash array in file app\Http\Requests\FormRequest.php

protected $dontFlash = ['password', 'password_confirmation', '_token'];

It gives me Token Mismatch error But when i click on submit button more than 2 times. And record is inserted 2 times which is unwanted behaviour.

It should give me error on 2nd attempt on submit at same time.

So in short What i need is if a user clicks on submit button single time it should insert record. and if he clicks on submit more than one time than it should give TokenMismatch Error.

Upvotes: 0

Views: 4094

Answers (1)

Prashant Deshmukh.....
Prashant Deshmukh.....

Reputation: 2292

You could set a token when you serve the form and check that against the database. When you submit the form, the token is checked and you can't submit it any more. Of course, it is still a good idea to do it front-end too as it is more visual for the user.

https://laracasts.com/discuss/channels/laravel/stopping-multiple-form-submission

Just searching for relevant answer and found this. Hope it will help in some way.

Upvotes: 1

Related Questions