hey guys i have this problem in my code , i dont know why is showing this error:
Method Illuminate\Database\Eloquent\Collection::students does not exist.
i tried to make many to many relation and this is my controller function:
public function attach_skill(Request $request) {
foreach($request->skills as $id){
dd(Skill::find($request->skills)->students()->attach($request->students));
return "done";
}
}
and this is my student model code:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Models\Task;
use App\Models\Skill;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Students extends Authenticatable
{
use HasFactory, HasApiTokens;
protected $fillable = [
'name',
'student_id',
'phone',
'password',
'email',
'major',
'GPA',
'Department',
'address',
];
protected $hidden = [
'password',
'remember_token',
'email',
'natioal_id'
];
public $table = "students";
protected $primaryKey = 'student_id';
public function tasks() {
return $this->belongsToMany(Task::class,'student_task','task_id','student_id');
}
public function taskk() {
return $this->belongsToMany(Task::class,'student_task','student_id','task_id');
}
public function skill() {
return $this->belongsToMany(Skill::class, 'student_skill', 'skill_id', 'student_id');
}
public function skilll() {
return $this->belongsToMany(Skill::class, 'student_skill', 'student_id','skill_id');
}
}
and this is my skill model code:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Students;
class Skill extends Model
{
use HasFactory;
protected $fillable = [
'skill_type',
];
protected $primaryKey = 'skill_id';
public function students() {
return $this->belongsToMany(Students::class,'student_skill','skill_id','student_id');
}
public function skilll() {
return $this->belongsToMany(Skill::class, 'student_skill', 'student_id','skill_id');
}
public $timestamps = false;
}
i want students and skills request in array becuse i have my skills and many students.
Because you're passing an array to find()
method that is wrong, pass $id
instead of $request->skills
, please do this if you're iterating in loop,
public function attach_skill(Request $request) {
foreach($request->skills as $id){
dd(Skill::find($id)->students()->attach($request->students));
return "done";
}
}