This will get multiple course ids
$courseId = DB::table('courses')->pluck('id');
instead you should just get one (maybe a random one?)
$courseId = DB::table('courses')->inRandomOrder()->value('id');
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello i encountered this problem: While trying to seed specific grades to specific courses i am not able to connect the different grades to a specific course:
This is the GradeSeeder
$courseId = DB::table('courses')->pluck('id');
$grades = [
[
'course_id' => $courseId->get('id'),
'exam' => 'Report',
'lowest_passing_grade' => 5.5,
'best_grade' => 10,
],
[
'course_id' => $courseId->get('id'),
'exam' => 'Assessment',
'lowest_passing_grade' => 5.5,
'best_grade' => 10,
]
];
foreach ($grades as $grade) {
Grade::create($grade);
}
And the Course model:
public function grades()
{
return $this->hasMany(Grade::class);
}
the grade model
public function course()
{
return $this->belongsTo(Course::class);
}
this is the grades migration
Schema::create('grades', function (Blueprint $table) {
$table->id();
$table->foreignId('course_id')->references('id')->on('courses');
$table->string('exam');
$table->decimal('lowest_passing_grade')->default(5.5);
$table->decimal('best_grade')->nullable();
$table->timestamps();
});
and this is my controller method
public function index()
{
$grades = DB::table('grades')
->join('courses', 'courses.id', '=', 'grades.course_id')
->select('courses.name', 'grades.*')
->get();
return view('grades.index', compact('grades'));
}
@tedo12334@gmail.com in that case; use the shift Collection method:
$courseId = DB::table('courses')->pluck('id');
$grades = [
[
'course_id' => $courseId->shift(),
'exam' => 'Report',
'lowest_passing_grade' => 5.5,
'best_grade' => 10,
],
Please or to participate in this conversation.