I am new to PHP and Laravel. I have learned much, but I am having a problem seeing my error in what should be a simple task.
I have a form which is populated from data in a MySQL database. When I submit it, it creates a new record instead of updating the existing record. Is is the form action I am using:
<form action="{{route('updateAlert', $alert->id)}}" method="post" name="saveAlert" id="saveAlert" class="needs-validation"
@csrf
@method("PUT")
///form fields here
</form>
Here are the two related routes. editAlert brings you to the form above. updateAlert is supposed to bring you to the update method on my AlertController.
Route::get('/alerts/edit/{id}', 'AlertController@edit')->name('editAlert');
Route::put('/alerts/edit/{id}', 'AlertController@update')->name('updateAlert');
Here is what my AlertController looks like:
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Alert $alert)
{
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
return redirect()->route('viewAlerts')->with('success', 'Your alert has been updated.');
}
What am I missing? I have the same basic code in another section of the app that is working as expected. Thanks in advance.
CodePudding user response:
You Are Not Fetching your row id. You need to use model and pass your id to your model to update any specific row.
Ex. I the model name just pass your model name.
public function update(Request $request, Alert $alert)
{
$alert = ModelName::find($alert);
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
return redirect()->route('viewAlerts')->with('success', 'Your alert has been updated.');
}
CodePudding user response:
To update things in Laravel, you need a query builder object; Alert $alert returns an object of the model, so it can not be used to update things.
Note: find method is a special method whose objects can be used to update records, unlike the "first" method.
So your code must be changed to:
public function update(Request $request, Alert $alert)
{
$alert = Alert::where('id', $alert->id); // or: Alert::find($alert->id);
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
}