I am new in Laravel I have two tables Student , Courses . Their relation is many to many, when I try to add new student and assign the student to many courses that already exist , it add new student correctly but can`t add to table student_course I use Laravel 5.7 .
In Student Model I define function courses
public function courses()
{
return $this->belongsToMany('App\Course');
}
And in Courses model I add
public function student()
{
return $this->belongsToMany('App\Student');
}
In studentController
public function store(Request $request , Courses courses)
{
Student::createStudent($request->all());
$courses = courses()->attach($request->courses);
return redirect('/admin/student')->with('success','Has been added');
}
In student create.blade
<select name='courses[]' style="width:220px;" multiple="multiple">
@foreach( $courses as $course )
<option value="{{$course->id}}">{{$course->name_courses}}</option>
@endforeach
</select>
This to select many courses.
The error that occurred that the courses is undefine variable in StudentController. I try to solve it but I have no idea how to.