Home > Back-end >  Laravel CRUD - Update doesn't work - doesn't make changes
Laravel CRUD - Update doesn't work - doesn't make changes

Time:04-21

Everything works great in CRUD, except for update.

My Controller:

    public function update(Request $request, $id)
{
    $post = Post::findOrFail($id);
    $post->update($request->all()); 
    return redirect('/posts');
}

CodePudding user response:

To answer this you need to know if that id is coming through properly. Do a dump($id); This will show you if it's null or something unexpected. I'd then wrap the $post in logic to rule out nulls or bad data. Technically if you are doing a post from the front your id will usually be

$request->id this being sent from a hidden input on the front.

I'd also use a first() because everything coming to this function should already be created and not be null since you're populating this from the database.

$post = Post::where('id',  $request->id)->first();

Next do a dump on $post dump($post); this will show you the post info. If you don't have any post info you have trouble and will require more troubleshooting. Then you can just do your save process, I personally like to to do a 1 to 1 save to make sure all values from the request are being properly handled. So it would be..

$post->column_name = $request->input_name;
$post->save();
return back()->with ('status', 'Record Updated!');

Then on the front you can display that status from session to show it was updated. One caveat using mass update is that you should make sure that the fields you are updating are fillable in the model.

CodePudding user response:

You need check your model at the first it should be something like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Crud extends Model
{
    protected $fillable = [
        'first_name', 'lastame', 'id',
       ];
}

then you have to use

dd('$post')

to see what you have then you can create your update like this:

public function update(Request $request, $id)
{
    $post = Post::findOrFail($id);
    $post->update($request->all()); 
    return redirect('/posts')->with('success', 'Data is successfully updated');;
}
  • Related