Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

danisemet's avatar

Array field always store the last value of the field into database.

Guys. help me working with array inputs on my project. this is the form

Siswa Siswa

My Controller:

public function store(Request $request) {

    foreach ($request->scores as $score)
    {
        $scr = new Assestment;
        $scr->year_id = $request->year_id;
        $scr->grade_id = $request->grade_id;
        $scr->clas_id = $request->clas_id;
        $scr->student_id = $request->student_id;
        foreach($request->lesson_id as $lesson)
        {
            $scr->lesson_id = $lesson;
        }
        $scr->score = $score;
        $scr->save();
    }

}

My Model: namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Assestment extends Model { protected $table = 'assestments';

protected $fillable = [
    'year_id', 'grade_id', 'clas_id', 'student_id', 'lesson_id', 'score',
];

public function students()
{
    return $this->belongsToMany('App\Models\Student');
}

}

i would like to make the value of field "scores[]" and "lesson_id[]" as array so that they store multiple data to database. but when i subit the form, the "lesson_id[]" always store the last value of the form. for example, the field "lesson_id[]" contains multiple values like "1, 2, 3 , 4", but the value stored into database is always "4 (the last value of the field)".

what should i do? plis help....

0 likes
3 replies
vtalbot's avatar

This part assign the id of the lesson to the column lesson_id and is replaced by the next lesson id of the array, so it is a normal behavior that it only save the last lesson:

foreach($request->lesson_id as $lesson)
{
    $scr->lesson_id = $lesson;
}

You should instead use something like:

$scr = new Assestment;
$scr->year_id = $request->year_id;
$scr->grade_id = $request->grade_id;
$scr->clas_id = $request->clas_id;
$scr->student_id = $request->student_id;
$scr->score = $score;
$scr->save();
$scr->lessons()->sync($request->lesson_id);

And you should have a pivot table since your assestment belongs to many lessons. https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

The table, named assestment_lesson, should have the columns assestment_id and lesson_id.

danisemet's avatar

it doesn't seems to work, Mr. vtalbot.

i remove the line:


public function lessons() 
{
    return $this->belongsToMany('App\Models\Lesson');
}
on my models because i do not actually need it. i just prepare that function for further coding.

the main problem is, how do i prevent the controller to store the last value of the "lesson_id[]" field?

Please or to participate in this conversation.