Home > Software design >  Laravel 9 Cannot UPDATE Data
Laravel 9 Cannot UPDATE Data

Time:07-24

CONTROLLER

    public function update(Request $request)
    {
        DB::table('bahanbaku')->where('id', $request->id)->update([
            'id_bb' => $request->id_bb,
            'nama_bb' => $request->nama_bb,
            'stok' => $request->stok
        ]);

        dd($request);
        return redirect('/bahanbaku');
    }

Sorry for my bad english, but in my case,

After Submit, Data still same, not change

Can you help me? T.T

CodePudding user response:

Id does not exist, this is quite basic, but i feel like there is some misunderstandings with Laravel. Just to get the basics down, in Laravel i would expect you to do the following.

  • Use models for database operations
  • Instead of passing the id on the request, pass it on URL parameters
  • Use model binding for getting your model.

Create your model, since it has a non standard table name define that. Add the properties you want to be filled when updating it as fillables.

use Illuminate\Database\Eloquent\Model;

class Bahanbaku extends Model {
   protected $table = 'bahanbaku';

    protected $fillables = [
        'id_bb',
        'nama_bb',
        'stok',
    ];
}

In your route, define the model as a parameter.

Route::put('bahanbaku/{bahanbaku}', [BahanbakuController::class, 'update']);

Now the logic can be simplified to this, which will automatically handle if the model is not found and give you a 404 error.

public function update(Request $request, Bahanbaku $bahanbaku)
{
    $bahanbaku->fill(
        [
            'id_bb' => $request->id_bb,
            'nama_bb' => $request->nama_bb,
            'stok' => $request->stok
        ],
    );
    $bahanbaku->save();
    
    return redirect('/bahanbaku');
}

To improve even more, i would look into utilizing form requests.

  • Related