KodaC's avatar
Level 1

CRUD: Prevent overwriting in case of error

I have a CRUD in which I generate a temporary hash

$myHash = \bin2hex(\random_bytes(8));
$hashValues = HashValue::where('hash_value', $myHash)->first();

In the create.blade.php I have a hidden input field

<input type="hidden" id="avatarHash" name="avatarHash" value="{{ old('myHash', $myHash) }}">

and process the value $hashValues if it is filled. When I submit the form, the hash in my create function changes and $hashValues is no longer correct. How can I ensure that the hash is only overwritten if my form has not yet been sent?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

One solution to prevent overwriting the hash in case of an error is to store the hash in the session before rendering the create view. Then, in the create function, check if the hash exists in the session and use that instead of generating a new one. Here's an example:

// In the controller function that renders the create view
$myHash = session('myHash') ?? \bin2hex(\random_bytes(8));
session(['myHash' => $myHash]);
return view('create', ['myHash' => $myHash]);

// In the create function
$myHash = session('myHash');
$hashValues = HashValue::where('hash_value', $myHash)->first();
if (!$hashValues) {
    // Handle error
}
// Use $myHash and $hashValues as needed

This way, the hash is only generated once per session and is not overwritten when the form is submitted with errors.

1 like

Please or to participate in this conversation.