How to get the user name from comment and user_id?

Viewed 72

I'm trying to get user name from user_id. I was not able to get the name. i have only store-action, didn't create show action.

Error massage: Trying to get property 'name' of non-object (View: /var/www/html/laravel-app/resources/views/bbs/show.blade.php)

CommentsController.php

    public function store(CommentRequest $request)
    {
        $comment  = new Comment; 
        $comment->comment = $request->comment;
        $comment->name = "";  
        $comment->post_id = $request->post_id;
        $comment->save();
        return redirect()->route('bbs.show', [$comment['post_id']])->with('commentstatus','');
    }

show.blade.php

              @forelse($post->comments as $comment)
                    <div class="border-top p-4">
                        <time class="text-secondary">
                            {{ optional ($comment)->user->name }} / 
                            {{ optional ($comment->created_at)->format('Y.m.d H:i') }} / 
                            {{ optional ($comment)->id }}
                        </time>

Comment.php

    /**
     * 
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }

    /**
     * 
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
1 Answers

First, you can store user_id in the comments table

CommentsController.php:-

public function store(CommentRequest $request)
    {
        $comment  = new Comment; 
        $comment->comment = $request->comment;
        $comment->user_id = Auth::id(); // pass user_id here
        $comment->name = "";  
        $comment->post_id = $request->post_id;
        $comment->save();

       dd($comment->user->name);

    }
    

show.blade.php:-

@forelse($post->comments as $comment)
                    <div class="border-top p-4">
                        <time class="text-secondary">
                            {{ $comment->user->name ?? '' }} / 
                            {{ $comment->created_at->format('Y.m.d H:i') }} / 
                            {{ $comment->id ?? '' }}
                        </time>

Comment.php:-

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $table = 'comments';
    protected $guarded = [];
    public function post()
    {
        return $this->BelongsTo('App\Post','post_id');
    }

    public function user()
    {
        return $this->BelongsTo('App\User','user_id');
    }

Related