To allow users to comment on a post, you have set up the relationships correctly in your models. However, there are a few improvements and clarifications that can be made to ensure everything works smoothly.
Models
-
User Model:
public function comments() { return $this->hasMany(Comment::class); } -
Post Model:
public function comments() { return $this->morphMany(Comment::class, 'commentable'); } -
Comment Model:
public function user() { return $this->belongsTo(User::class); } public function commentable() { return $this->morphTo(); }
Creating a Comment
To create a comment on a post, you can use the create method on the comments relationship of the Post model. However, you need to ensure that the user_id is correctly set. Here is the corrected and improved way to do it:
use Illuminate\Support\Facades\Auth;
// Assuming $post is an instance of the Post model
$post->comments()->create([
'user_id' => Auth::id(), // Use Auth::id() to get the authenticated user's ID
'text' => 'This is a comment'
]);
Alternative Method
If you want to make the process more streamlined, you can create a method in your Post model to handle the creation of comments. This can encapsulate the logic and make your controller code cleaner.
Post Model Method
public function addComment($text) {
return $this->comments()->create([
'user_id' => Auth::id(),
'text' => $text
]);
}
Using the Method in Controller
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
$post = Post::find($postId); // Assuming $postId is the ID of the post
$post->addComment('This is a comment');
Summary
- Ensure you use
Auth::id()to get the authenticated user's ID. - You can encapsulate the comment creation logic in a method within the
Postmodel for cleaner code.
By following these steps, you can efficiently allow users to comment on posts in your application.