0

So I have been building this simple Guest book where people leave comments. Ive linked the user model to the comment model and have tried returning the user that posted the comment however I always get an error. Ive made a Ticketing program before this using the same code and it worked and works fine still. See below

Comment Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
  public function user()
  {
    return $this->belongsTo('User::class');
  }
}

User Model

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function comments()
    {
      return $this->hasMany(Comment::class);
    }
}

And this is the controller where I am trying to return the results

<?php

namespace App\Http\Controllers;
use App\Comment;
use App\User;
use Auth;
use Illuminate\Http\Request;

class HomeController extends Controller
{

    public function index()
    {
      $comments = Comment::all();
      $user = Auth::user();
      $test = User::all();
      $average = number_format((Comment::avg('rating')),2, '.', '');
      dd($comments->user);
      return view('welcome')->withComments($comments)->withUser($user)->withAverage($average);

    }
}

Everytime I try and DD the result I get the error
Property [user] does not exist on this collection instance.

I am 100% stumped why this will work on one project and not another. I even rebuilt this little app to see if it was something I had done and I still get the same result.

  • return $this->belongsTo('User::class'); should be return $this->belongsTo(User::class); or return $this->belongsTo('App\Models\User'); – Indra Dec 13 '17 at 13:20
  • also $comments it's a collection of object so you need to access the user per each object. Try $comments->each(function($value){ dump($value->user->name; }); – Indra Dec 13 '17 at 13:22
  • If you want just the comments by the current user \Auth::user()->comments; You should have gotten a hint here: Property [user] does not exist on this collection instance – Indra Dec 13 '17 at 13:23

1 Answers1

0

You're trying to get property of a collection, not an object. So do this:

foreach ($comments as $comment) {
    dump($comment->user); // $comment is an object
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279