muuucho's avatar
Level 11

Can't update model

Nothings happen when i try to save in the update() method:

public function edit(Pub $pub)
    {
        $pub = Pub::with(['tags', 'pubType'])->where('pubs.id', '=', $pub->id)->firstOrFail();
        $pubTypes = PubType::all();
        $tags = Tag::all();
        return view('pubs.edit', ['pub' => $pub, 'pubTypes' => $pubTypes, 'allTags' => $tags]);
    }

    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' => 'Fieled must contain :min signs.',
        ]);
        #$request->vat ? 1 : 0 ?? 0;
        $pub->save([$validated]);
        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.');
    }

I can echo out $validated and it is an array as expected, but nothing gets saved to the table pubs

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
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:

  1. Validation: The $validated array contains the validated data from the request.
  2. Filling the Model: Use the fill method to assign the validated data to the model's attributes.
  3. Saving the Model: Call the save method on the model instance to persist the changes to the database.
  4. 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

Please or to participate in this conversation.