Modify Driver to update do not insert

0

I have this driver to upload two tables at once from a form works well but I have the question of how I can modify it so that instead of inserting in the Point table the update someone gives me a hand ?? thank you ..

  public function store(Request $request)
{

  $dsa = Dsa::Create($request->all());
  $in = new Point;
  $in->user_id = auth()->user()->id;
  $in->uni = $request->get('uni');
  $in->save();

    return redirect()->route('dsa.edit', $dsa->id)->with('info', 'Categoría creada con éxito');
}
    
asked by jorge 24.10.2018 в 18:58
source

2 answers

1

To update a record instead of creating a new record you must use a different method, if we follow API REST it must be of type PUT . Follow these steps:

1. Create route

routes / web.php

Route::post('/ruta/para/crear/registro', 'AlgunControlador@store');
// nuevo:
Route::put('/ruta/para/crear/registro/{id}', 'AlgunControlador@update');

As you can see, we have added a new route of type PUT and we are adding a route variable which will bring the id of the object to be updated. We are mapping this route for the method update of the controller AlgunControlador .

2. Implement the new method in the controller

app / Http / Controllers / AlgunControlador.php

public function store(Request $request)
{
    // your code
}

public function update(Request $request, $id)
{
    // buscamos el objecto
    $object = Modelo::findOrFail($id);
    // actualizamos los datos
    $object->udpate($request->only(['field_1', 'field_2', 'etc']));

    return redirect()->route('nombre_de_ruta')->with('info', 'Categoría actualizada con éxito');
}
    
answered by 25.10.2018 в 05:18
1

Finally .. I share it in case I could serve someone no matter how simple it is ..

public function store(Request $request)
{

  $dsa = Dsa::Create($request->all());
  $in = Point::where('user_id', auth()->user()->id)->first();
  if ($in){

  $in->uni = $request->get('uni');
  $in->save();
  }
  else
  {
    $in = new Point;
    $in->user_id = auth()->user()->id;
    $in->uni = $request->get('uni');
    $in->save();
  }
    
answered by 29.10.2018 в 17:37