I am learning Laravel and there is one thing I cannot solve.
What do I have:
Table of Users, Posts, Comments and corresponding Models
User.php:
public function comments() { return $this->hasMany(Comment::class); }
public function publishComment(Comment $comment)
{
$this->comments()->save($comment);
}
Post.php:
public function comments() { return $this->hasMany(Comment::class); }
Comment.php:
public function post() { return $this->belongsTo(Post::class); }
public function user() { return $this->belongsTo(User::class); }
What do I want?
Since I have Blog, one logged user can create many posts (this works). But same logged user can create many comments to one post. (User has many comments, post has many comments).
Tables:
User: | id | name | email | password
Comment: | id | user_id | post_id | body
Post: | id | user_id | title | body
What have I tried? I created controller
CommentsController:
class CommentsController extends Controller
{
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
auth()->user()->publishComment(
new Comment(request('body'));
);
return back();
}
And in my blade file I simply want $comment->user->name (get name of user who does the comment belongs to)
Error I get: Trying to get property of non-object
<?php echo e($comment->user->name); ?>
Any help would be appreciated.