Prevent that when reloading a page recreate the same record

1

How do I avoid reloading the page to which a user is redirected after adding a record in laravel 5.3, to recreate the same record? the idea is that it does not do it, but in case the user refreshes the screen for some reason the same record is not created again.

    
asked by DVertel 04.11.2016 в 06:12
source

2 answers

1

There are several possible solutions for this typical problem, I am going to write you some of them:

  • If you have a single field for each record (for example, an email address, an identifier of any kind, a phone number, etc.) you can use the validation unique and avoid this problem.
  • In the controller (it could even be a type of validation in the request) you can compare (or delegate the comparison) the last record inserted in the database by that user (assuming you need to be registered to record that information) with the data that you try to enter again when reloading and determine if they are valid or not according to your rules.
  • Perhaps the simplest: to do a redirection to another route after saving the data, that way if the person reloads the page, it will simply be doing a simple GET.

An example of the last point, for which you need three routes:

// muestras el formulario de creación
public function create()
{
    // hacer otras cosas
    return view('articulo.crear');
}

// almacenas el registro
public function store(Request $request)
{
    // guardarlo ...
    return redirect()->route('articulo.creado', ['id' => $id]);
    // o puedes redirigir a un dashboard, o al home, lo que quieras
}

// muestras una página informando que fue creado
public function created($id)
{
    // obtener datos?
    return view('articulo.creado', compact('articulo'));
}
    
answered by 04.11.2016 / 14:48
source
0

I do not know how larabel works, but personally when I want to avoid that the user has the possibility to refresh the page, I use a redirect, and I pass the values required by parameters.

    
answered by 04.11.2016 в 15:44