Retrieving intermediate table specific columns Hey there I am creating LMS using laravel, so I face some problems
This is my Models
Course
User which has roles -student,instructor,admin etc.
course_user which has columns course_id,user_id,status
I created relationships
What I need first is to check
If user enrolled course ,then if user enrolled the course to check IsStatus column is 1.
That means User is Manually bought the course.
Second the admin panel
User
course
lesson
video
course_user which is an intermediate table for all students
How to get each instructor courses,users,lessons and video
The first problem will be solved by creating many to many relationships.
In your User model:
public function courses()
{
return $this->belongsToMany(Course::class);
}
public function statuses()
{
return $this->hasMany(Status::class);
}
In your Course model:
public function users()
{
return $this->belongsToMany(User::class);
}
public function statuses()
{
return $this->hasMany(Status::class);
}
You must create a table for the many to many relationships, you can see an example at official Laravel documentation: https://laravel.com/docs/5.7/eloquent-relationships#many-to-many .
After that, you can check user's course like that:
if($user->courses()->find($course_id)){
//check IsStatus
if($user->statuses()->find($course_id)->IsStatus){
//some actions
}
}
The second problem will also be solved by creating relationships between instructor and other models.
You are using many-to-many relationship between course table and user table. On you relationship you should specify which columns
...
public function courses()
{
return $this->belongsToMany(Course::class)->withPivot('column1', 'column2');
}
than,
$user = App\User::find(1);
foreach ($user->courses as $role) {
echo $role->pivot->column1;
}
https://laravel.com/docs/5.7/eloquent-relationships#many-to-many
My user Model.
public function courses(){
return $this->hasMany(Course::class);
}
public function students()
{
return $this->hasManyThrough(User::class,Course_user::class,'user_id','user_id','id');
}
There is a User Model
There is a Course Model
There is a course_user , which is an Intermediate table.
What I need is to get
##Instructor->students
Please sign in or create an account to participate in this conversation.