I have three table Students ,Subject and Pivot table name 'student_subject' ,when using attach(1) work it (Insert data in pivot table) .
but when using attach($request -> subject) dont work
why ? i dont now
Model :
class Student
class Student extends Model
{
protected $fillable=['user_id','FullName','age','address','father_ID','photo_id','class_id'];
public function subject(){
return $this->belongsToMany(Subject::class);
}
public function classes(){
return $this->belongsTo('App\classes','class_id');
}
public function user(){
return $this->belongsTo('App\User');
}
public function photo(){
return $this->belongsTo('App\photo');
}
//
}
class Subject :
class Subject extends Model
{
protected $fillable = ['name','user_id'];
//
public function student()
{
return $this->belongsToMany(Student::class);
}
}
Student Controller
public function store(Request $request)
{
$input =$request->all();
$user =Auth::user();
if ($file = $request->file('photo_id')){
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$photo = photo::create(['file'=>$name]);
$input['photo_id']=$photo->id;
}
$student = $user->student()->create($input);
// $student = $user->student()->create($input);
$request['student_id'] = $request->id;
$student->subject()->attach(1);
dd($student);
return redirect('admin/students');
Create View :
@foreach($subjects as $subject)
<tr>
<td>
<div class="form-group" {{}}>
{!! Form::label('name', $subject) !!}
{!! Form::checkbox('name',$subject,false, ['class'=>'form-control'])!!}
</div>
</td>
</tr>
@endforeach
Pivot table 'student_subject'
public function up()
{
Schema::create('student_subject', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('student_id');
$table->unsignedBigInteger('subject_id');
// $table->foreign('student_id')->references('id')->on('students');
$table->foreign('student_id')->references('id')->on('students');
$table->foreign('subject_id')->references('id')->on('subjects');
});
}