0

Здравствуйте! Подскажите пожалуйста. Не удается получить имя комментатора.

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation 

ErrorException in HasAttributes.php line 403:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation (View: D:\OpenServer\domains\photograph.loc\resources\views\posts\post.blade.php)

Вот эта строчка: {{$comment->user->name}}. Именно после взаимодействия с comments->user выводится ошибка.

post.blade.php

 @extends('layout')

  @section ('content')
  <article class="post">
    <span>Статью написал: {{$post->user->name}}</span></br>
    <time>{{$post->created_at->toFormattedDateString()}}</time>
    <h1>{{$post->title}}</h1>
    <div class="content">
      {{$post->body}}
    </div>
    @if (count($post->comments))
    <div class="comments">
      <h3>Комментарии</h3>
      <ul class="list-group">

        @foreach ($post->comments as $comment)
          <li class="list-group-item">
            <span class="date">Комментарий оставлен {{$comment->user->name}} в {{$comment->created_at->diffForHumans()}}</span>
            <div class="body-comment">{{$comment->body}}</div>
          </li>
        @endforeach
      </ul>
      <hr>
    @endif
    @if (Auth::check())
      <div class="card">
        <div class="card-block">
          <form method="post" action="/posts/{{$post->id}}/comments">
            {{csrf_field()}}
            <div class="form-group">
              <textarea name="body" placeholder="Ваш комментарий" class="form-control"></textarea>
            </div>
            <button type="submit" class="btn btn-inverse">Опубликовать</button>
          </form>
        </div>
      </div>
    @else
    <div class="card">
      <div class="card-block">
        <span>Вы не можете оставлять комментарии.</span>
      </div>
    </div>
    @endif
  </div>
  </article>
  @endsection

routes/web.php

Route::get('/posts/{post}', 'PostsController@show');

PostsController.php

public function show(Post $post)
{
  return view('posts.post', compact('post'));
}

Comment.php

<?php

namespace Photo;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = ['body', 'user_id', 'post_id'];


    public function user()
    {
      $this->belongsTo(User::class);
    }
    public function post()
    {
      $this->belongsTo(Post::class);
    }

}

User.php

<?php

namespace Photo;

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

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts()
    {
      return $this->hasMany(Post::class);
    }

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

    public function publish(Post $post)
    {
      $this->posts()->save($post);
    }
}

Post.php

<?php

namespace Photo;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Post extends Model
{
    protected $guarded = [];

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

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

    public function scopeFilter($query, $filters)
    {
      if ($month = $filters['month']){
        $query->whereMonth('created_at', Carbon::parse($month)->month);
      }

      if ($year = $filters['year']){
        $query->whereYear('created_at', $year);
      }
    }

    public static function archives()
    {
      return static::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
      ->groupBy('year', 'month')
      ->orderByRaw('min(created_at) desc')
      ->get()
      ->toArray();
    }
}

1 ответ 1

2

Вы в relation-методе забыли вернуть сам relation:

public function user()
{
  // тут должен быть return
  return $this->belongsTo(User::class);
}
public function post()
{
  // и тут тоже
  return $this->belongsTo(Post::class);
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.