I create a many-to-many relationship, where many projects can be assigned to many users. My problem is that I do not know how to display projects assigned to a given user. . Currently, all available projects are displayed. I created pivot table, where after adding the project I store the project id and user id. This is my code:
User.php
public function projects()
{
return $this->belongsToMany('App\Project')->withTimestamps();
}
Project.php
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
ProjectsController.php
public function projects()
{
$projects = Project::latest()->get();
return view('pages.projects')->with('projects', $projects);
}
migrations:
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->longText('p_name')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('project_user', function (Blueprint $table) {
$table->unsignedInteger('project_id');
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
Eager load users in your controller:
public function projects()
{
$projects = Project::latest()->with('users')->get();
return view('pages.projects')->with('projects', $projects);
}
In your view:
#foreach($projects as $project)
#foreach($project->users as $user)
#endforeach
#endforeach
If you want to display projects assigned to a user you would do something like:
public function projectsByUser($userId)
{
$user = User::findOrFail($userId);
$projects = $user->projects;
return view('pages.projects')->with('projects', $projects);
}
and keep the view like:
#foreach($projects as $project)
#endforeach
Related
I have a store that is using a payment package
Now I want to show the items that were purchased, but I run into this problem
Controller
public function mycourse()
{
$courses = PurchasedCourse::where('user_id', Auth::id())
->with('course')
->get();
dd($courses);
return view('student.courses.mycourse', [
'courses' => $courses
]);
}
Model
public function course()
{
return $this->belongsTo(Course::class, 'id');
}
Migration
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id('id');
$table->string('name')->unique();
$table->string('start');
$table->string('end');
$table->integer('price');
$table->string('jalasat');
$table->string('zarfiat');
$table->text('tozih');
$table->integer('hit');
$table->string('department');
$table->string('thumbnail');
$table->tinyInteger('status')->default(0);
$table->string('slug')->unique();
$table->timestamps();
});
}
Your relationship method is wrong. The syntax for the belongsTo() method is
belongsTo(class, ?foreign_id, ?related_id). In your case, it should be:
public function course()
{
return $this->belongsTo(Course::class, 'course_id', 'id');
}
or just
public function course()
{
return $this->belongsTo(Course::class);
}
since your columns follow Laravel's naming conventions.
I am getting error in Laravel 5.7 while creating relationship, I have created a relationship as: Question.php:
public function diffi_lvl() {
return $this->belongsTo('App\DifficultyLevel');
}
and DifficultyLevel.php:
public function questions() {
return $this->hasMany('App\Question');
}
after that I used:
#foreach ($questions as $question)
{{ dd($question->diffi_lvl()->diffi_lvl_name) }}
#endforeach
and QuestionController.php:
public function index()
{
$questions = Question::all();
return view('questions.index', compact('questions'));
}
difficulty level migration:
public function up()
{
Schema::create('difficulty_levels', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('diffi_lvl_name');
$table->timestamps();
});
}
and the question migration:
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->text('question');
$table->unsignedInteger('difficulty_level_id');
$table->foreign('difficulty_level_id')->references('id')->on('difficulty_levels');
$table->timestamps();
});
}
but it's giving me this error as;
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$diffi_lvl_name
Note: I also used this {{ dd($question->diffi_lvl->diffi_lvl_name) }} getting Trying to get property of non-object
Change your relationship as follows:
public function diffi_lvl() {
return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}
public function questions() {
return $this->hasMany('App\Question', 'difficulty_level_id');
}
Then, the following should work:
#foreach ($questions as $question)
{{ dd($question->diffi_lvl->diffi_lvl_name) }}
#endforeach
For more information, read the documentation on Defining Relationships.
Edit: Actually, it seems just doing the following should work:
public function diffi_lvl() {
return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}
public function questions() {
return $this->hasMany('App\Question');
}
You already fixed first error with using
$question->diffi_lvl->diffi_lvl_name
And for second error there are some possibilities.
There is no DifficultyLevel attached to your Question model
We have to see your table structure.Maybe you mapped wrongly your foreign keys.Is your foreign key named "difficulty_level_id" in "questions" table?
I'm trying to use a belongsToMany relation, i never had any problems with it but for some reason it returns empty now.
But, if i check with tinker, i get array with data in it returned
I've set up my relation in the User model like this:
// linking with table tag
public function tags(){
return $this->belongsToMany('App\Tag','tag_user','user_id','tag_id');
}
Tag model:
public function user(){
return $this->belongsToMany('App\User','tag_user','tag_id','user_id');
}
PostController
public function create()
{
// bringing user details to show his preferneces
$user_id = Auth::user()->user_id;
$user = User::find($user_id)->first();
//post_types
$types= PostType::pluck('name', 'post_type_id');
return view('user.create_post')->with('user', $user)->with('types',$types);
}
In view:
#foreach ($user->tags as $tag)
<label class = "btn btncategory">
<input type = "checkbox"
name = "tag_selected[]"
value = "{{$tag->tag_id}}" >
{{$tag->tag_name}}
</label>
#endforeach
Migrations
tags
Schema::create('tags', function (Blueprint $table) {
$table->increments('tag_id');
$table->string('tag_name')->unique();
$table->integer('type');
$table->integer('used_time')->default('0');
$table->timestamps();
});
Schema::create('tag_user', function(Blueprint $table){
$table->integer('user_id');
$table->integer('tag_id');
$table->primary(['user_id', 'tag_id']);
});
users
Schema::create('users', function (Blueprint $table) {
$table->increments('user_id');
$table->string('user_name')->unique();
$table->string('fname')->nullable();
$table->string('lname')->nullable();
... etc etc
So, I'm trying to create a relationship where users can follow other users or follow categories.
My intuition says that what I've done so far is not the right way of doing things. I'm especially confounded by how to create the follower - followee relationship.
TABLES:
Users
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->string('first_name');
});
}
Categories
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category');
});
}
Follows
public function up()
{
Schema::create('follows', function (Blueprint $table) {
$table->increments('id');
$table->integer('follower_id');
$table->integer('followee_id')->nullable();
$table->integer('category_id')->nullable();
});
}
MODELS:
User
class User extends Model implements Authenticatable
{
public function follows()
{
return $this->hasMany('App\Follow');
}
}
Category
class Category extends Model
{
public function follows()
{
return $this->hasMany('App\Follow');
}
}
Follow
class Follow extends Model
{
public function post()
{
return $this->belongsTo('App\User');
}
public function source()
{
return $this->belongsTo('App\Category');
}
}
According to your scenario, it is recommended that you use Polymorphic Many To Many relationship.
Schema:
users
id - integer
...
categories
id - integer
...
followables
user_id - integer
followable_id - integer
followable_type - string
Models:
User:
public function followers()
{
return $this->morphToMany(User::class, 'followables');
}
public function following()
{
return $this->morphedByMany(User::class, 'followables');
}
Category:
public function followers()
{
return $this->morphToMany(User::class, 'followables');
}
Then you can create the relationship like:
When following an User:
$user->followers()->create(['user_id' => 12])
When following a Category:
$category->followers()->create(['user_id' => 25])
Hope it helps.
I find the pivot tables pretty complicated and I don't see what to do next or what I am doing wrong, I've found some tutorials but didn't help me in my needs.
I have a projects and users with a many-to-many relation.
One project hasMany users and One user hasMany projects.
What I have now leaves projects without a relationship to a user.
This is what I have so far:
Projects table
class CreateProjectsTable extends Migration {
public function up()
{
Schema::create('projects', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->date('completion_date');
$table->integer('completed')->default(0);
$table->integer('active')->default(0);
$table->timestamps();
});
}
Users table
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->integer('company_id');
$table->integer('project_id');
$table->integer('usertype_id')->default(0);
$table->string('username');
$table->string('password');
});
}
Project User table (pivot)
class CreateProjectUsersTable extends Migration {
public function up()
{
Schema::create('project_users', function(Blueprint $table)
{
$table->increments('id');
$table->integer('project_id')->references('id')->on('project');;
$table->integer('user_id')->references('id')->on('user');;
});
}
User model
public function projects() {
return $this->belongsToMany('App\Project', 'project_users', 'user_id', 'project_id');
}
Project model
public function users() {
return $this->belongsToMany('App\User', 'project_users', 'project_id', 'user_id');
}
Project controller
public function index(Project $project)
{
$projects = $project->with('users')->get();
dd($projects);
$currenttime = Carbon::now();
//return view('project.index', array('projects' => $projects, 'currenttime' => $currenttime));
return view('user.index', compact('projects'));
}
The relationship in your User model is not correct. You have to swap the keys.
public function projects() {
return $this->belongsToMany('App\Project', 'project_users', 'user_id', 'project_id');
}
Edit regarding latest comment:
Don't think about the pivot table, as long as you have your relations setup correctly, which I believe they are, Laravel handles all of that for you.
Now $projects->users does not make any sense because projects does not have users. projects is just a collection of Project. Each Project within that collection will have a users relation. You would have to iterate through the collection to view each Project's users.
foreach($projects as $project) {
foreach($project->users as $user) {
echo $user;
}
}