Level 58
It looks like the issue lies in how you're attempting to save the validated data to the model. The save method should be called on the model instance itself, and you should assign the validated data to the model's attributes before calling save.
Here's a corrected version of your update method:
public function update(Request $request, Pub $pub)
{
$validated = $request->validate([
'name' => ['required', 'min:3', 'max:255'],
'pub_type_id' => ['nullable', 'integer'],
'vat' => ['accepted'],
],[
'name.min' => 'Field must contain :min signs.',
]);
// Assign the validated data to the model's attributes
$pub->fill($validated);
// Save the model
$pub->save();
// Update the tags
PubTag::where('pub_id', '=', $pub->id)->delete();
if (!empty($request->input('tags'))) {
foreach ($request->input('tags') as $tag) {
PubTag::create(['pub_id' => $pub->id, 'tag_id' => $tag]);
}
}
return redirect()->route('pubs.index')
->with('success', 'Pub updated successfully.');
}
Explanation:
-
Validation: The
$validatedarray contains the validated data from the request. -
Filling the Model: Use the
fillmethod to assign the validated data to the model's attributes. -
Saving the Model: Call the
savemethod on the model instance to persist the changes to the database. - Updating Tags: Delete existing tags and create new ones based on the input.
This should ensure that your model is updated correctly with the validated data.
1 like