duai5344
2016-03-02 20:24
浏览 117
已采纳

Laravel Relationship方法必须返回一个Relation类型的对象

I've been scouring google trying to figure out a solution. I'm getting the:

ErrorException in Model.php line 2755: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

error when I try to go to my posts index page, and a just can't figure out where it's coming from. I can get to the page when I redirect from creating a post, but after that I get the error. Supposedly it's supposed to come from not returning a relationship, but here's my relationships and code:

Post

public function category() 
{
    return $this->belongsTo('App\Category', 'category_id');
}

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

User

public function roles() 
{
    return $this->belongsToMany('App\Role')->withTimestamps();
}
public function posts()
{
    return $this->hasMany('App\Post', 'user_id');
}

Role

 public function users() 
{
    return $this->belongsToMany('App\User');
}

Category

public function posts()
{
    return $this->hasMany('App\Post', 'category_id');
}

index.blade.php

@extends('app')

@section('content')
    <h1>Posts</h1>

    @if (Auth::check()) 
        @if (Auth::user()->isAdmin())
            <a href="/post/create">Create a Post</a>
        @endif
    @endif
    @foreach ($posts as $post)
        @include('includes.post', ['post' => $post, 'link' => true])
    @endforeach
@stop

and post.blade.php

<div class="post">
    <div class="div">
        <div class="postCategory">
        
        </div>
        @if($link)
            <a href="/post/{{ $post->id }}"><h2>{{ $post->title }}</h2></a>
        @else
            <h2>{{ $post->title }}</h2>
        @endif
        <p>{!! $post->body !!}</p>
        <p>{{ $post->category->name }}</p>
        <p>Posted by <a href="/user/{{ $post->user->username }}">{{ $post->user->username }}</a> at {{ $post->created_at }}</p>
        
        @if(Auth::check())
            @if($post->user->username == Auth::user()->username || Auth::user()->isAdmin)
                {!! Form::open(['method' => 'delete', 'route' => ['post.destroy', $post->id]]) !!}
                    <input type="submit" value="Delete Post" onclick="return confirm('Are you sure?')"></input>
                {!! Form::close() !!}
            @endif
        @endif
        
    </div>
</div>

</div>
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dttl3933 2016-03-02 20:57
    已采纳

    Before opening the form in post.blade, the last check you do is:

    Auth::user()->isAdmin
    

    In the other file, you check:

    Auth::user()->isAdmin() //note the ()
    

    Add them where missing

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题