How to post a custom value from laravel controller

Viewed 223

I'm trying to add a value from controller and send it to mysql along with the other input that I get from the view. How do I supposed to do it?

I tried using array_merge, tried to put them at the same variable and send it with Laravel's create but to no avail.

Here's the code

The Value

 $id = 0;
 $id++;

 $time = "2019-01-01 00:00:00";
 $date = new Carbon( $time );
 $d = $date->format('Y');

   $fmipa = 0;
   $fkh = 0;
   $lastNumber = 0;
   $fk = $request->get('fakultas');
   if($fk == 'FMIPA'){
     $fmipa++;
     $fk = 42;
     if($fmipa < 10){
        $fmipa="00". $fmipa;
        $lastNumber = $fmipa;
     }else if($fmipa < 100){
        $fmipa="0" . $fmipa;
        $lastNumber = $fmipa;
     }else{
        $fmipa = $fmipa;
        $lastNumber = $fmipa;
     }
   }else{
     $fkh++;
     $fk = 41;
     if($fkh < 10){
       $fkh="00". $fkh;
       $lastNumber = $fkh;
     }else if($fkh < 100){
       $fkh="0" . $fkh;
       $lastNumber = $fkh;
     }else{
       $fkh = $fkh;
       $lastNumber = $fkh;
     }
    }

$nim = $d . $fk . "101" . $lastNumber;

The Store() function


    $validator = Validator::make($request->input(), array(
     'nama' => 'required',
     'alamat' => 'required',
     'fakultas' => 'required',
    ));

    if ($validator->fails()) {
      return response()->json([
        'error'    => true,
        'messages' => $validator->errors(),
      ], 422);
    }

   $mahasiswa = Dashboard::create($request->all() + ['nim' => $nim]);


   return response()->json([
      'error' => false,
      'mhs'  => $mahasiswa,
   ], 200);

I seperate them to make it easy to read, but in case you're wondering the value's code is right in the store() function.

I expect it to post the value to the database and yet what I got from XHR's Response is

500 Internal Server Error

and

SQLSTATE[HY000]: General error: 1364 Field 'nim' doesn't have a default value

2 Answers

Replace store function as below

$dashboard = new Dashboard();
$dashboard->nama = $request->nama;
$dashboard->alamat = $request->alamat;
$dashboard->fakultas = $request->fakultas;
$dashboard->nim = $nim;
$dashboard->save();

The error occurred because your table dashboards of column nim is not nullable and it does not have a default value.

Inside your model Dashboard

protected $fillable = [... , 'nim'];

When you tried to create a dashboard, you are not giving value to the nim, which is causing the error.

If you do want the nim column to be nullable, you can add the functionality in you migration file.

Migration File

...
$table->string('nim')->nullable();
...

Re run your migration using php artisan migrate:refresh

If you want it to manually check, you can try in the DashboardController

//If request does not have nim
if(!$request->has('nim') && !empty($request->nim)){
    $request->nim = "";
}
Related