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.
Related
I'm building a basic forum, there are many topics and each topic has comments, a comment or "commentable" can be a a comment or a reply (commented a comment), this is because I want to have nested comments, that's where parent_id is useful. I'm wondering if my polymorphic relationship is the best way to achieve this so I'm open to any suggestions. The first issue I came up with is I don't know hw to do ajax pagination of topic->comments ..., I thought with something like Comment::whereHas('topic') ... but my comments dont' have a topic relationship defined in the model.
I'm using laravel advanced ajax pagination, how can I paginate comments?
Topic model:
class Topic extends Model
{
protected $table = 'topics';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
}
public function up()
{
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->text('body');
$table->string('url')->unique();
$table->string('slug')->unique();
$table->boolean('isVisible')->default(false);
$table->timestamps();
});
}
}
Comment model:
class Comment extends Model
{
protected $table = 'comments';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function replies()
{
return $this->hasMany('App\Models\Comment', 'parent_id');
}
}
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned();
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->text('body');
$table->timestamps();
});
}
This is where I took inspiration:
Comment Model:
public function commentable()
{
return $this->morphTo();
}
public function comments()
{
return $this->hasMany(Comment::class , 'parent_id' , 'id');
}
public function setCommentAttribute($value)
{
$this->attributes['comment'] = str_replace(PHP_EOL , "<br>" , $value);
}
Post Model:
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
And Controller:
public function show_comments(Post $post)
{
$comments = $post->comments()
->where('approved' , 1)
->where('parent_id', 0)
->latest()
->with(['comments' => function($query) {
$query->where('approved' , 1)->latest();
}])->get();
dd($comments);
return view('post',compact('comments'));
}
Database table Comments:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned()->default(0);
$table->boolean('approved')->default(0);
$table->text('comment');
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->timestamps();
});
$dd($comments) returns #items: [] or Empty. There are database records and I can access them with another methods.
I did searching alot before asking but no luck.
I was trying to resolve the same issue for a few hours. For anyone searching for the answer :
Check if the commentable_type field in comments table has properly formatted route strings
'commentable_type' => 'App/Models/Comment', // Does not work
'commentable_type' => 'App\Models\Comment', // Works 🥳
I have 4 tables, 1->user, 2->category, 3->comment, 4->post
I want to get the category for the related post that user already commented
SELECT kategoris.* FROM kategoris
INNER JOIN yazis on yazis.kategori_id = kategoris.id
INNER JOIN yorums on yorums.yazi_id = yazis.id
INNER JOIN users on users.id = yorums.user_id
where users.id = 1
Relations
Depending on how your models are setup, this is how the query should be with Eloquent
$category = Post::whereHas('comments', function($query) {
$query->where('user_id', auth()->user()->id);
})->first()->category;
Update:
This is how your models and table migrations should look
User has many posts and comments
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
Category has many posts
public function posts()
{
return $this->hasMany(Post::class);
}
Post belongs to a category and a user, has many comments
public function category()
{
return $this->belongsTo(Category::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Posts Table Migration
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
Comment belongs to a post and a user
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Comments Table Migration
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
Let's populate some data like this...
Database Seeder
$user = factory(User::class)->create([]);
$category = Category::create([]);
$post = $user->posts()->create(['category_id' => $category->id]);
$post->comments()->create(['user_id' => $user->id]);
And get the category of the post that the authenticated user commented on with the query above...
Hope this helps :)
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
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;
}
}