I encountered difficulty with the update function. Even after the data has been updated, it does not change. Is there something wrong with my code?
Controller
public function update(Request $request, Mahasiswa $mahasiswa)
{
$validatedata = $request->validate([
'nim' => 'required|size:8|unique:mahasiswas,nim,'.$mahasiswa->id,
'Nama' => 'required|min:3|max:50',
'jenis_kelamin' => 'required|in:P,L',
'jurusan' => 'required',
'alamat' => '',
]);
Mahasiswa::where('id',$mahasiswa->id)->update($validateData);
//$mahasiswa->update($validatedata);
return redirect()->route('mahasiswas.show',['mahasiswa' => $mahasiswa->id])
->with('pesan',"Update data {$validatedata['nama']} berhasil");
}
Model
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class mahasiswa extends Model
{
use HasFactory;
protected $guarded = [];
}
Migration
public function up()
{
Schema::create('mahasiswas', function (Blueprint $table) {
$table->id();
$table->char('nim', 8)->unique();
$table->string('nama');
$table->char('jk',1);
$table->string('jurusan');
$table->text('alamat')->nullable();
$table->timestamps();
});
}
2
Answers
Variable names are case-sensitive. So
$validatedata
and$validateData
are considered two different variables. You’ve validated the data and stored it in the$validatedata
variable, but when you’re updating theMahasiswa
model, you’re using$validateData
which is undefined.Your code has some issues that need to be addressed. Your model should be Capitalized (
class Mahasiswa
). On your controller, you don’t need to search for the instance as you already are receiving it on the controller (Mahasiswa$mahasiswa
). You’re saving your validated data in$validatedata
but then you’re referring to it as$validateData
. finally, make sure all the data you want to save has an corresponding table column (everything should be lowercase, and if you want to storejenis_kelamin
you should add a column for it).