尝试通过关联获取非对象问题的属性

时间:2018-04-13 13:53:11

标签: laravel laravel-5 laravel-5.4

我正试图通过创建和存储表单在我的一个论坛中发布一个新线程,并在尝试将该线程与我发布该线程的论坛关联时遇到错误。有人知道问题在哪里吗?

问题:

Trying to get property of non-object
at HandleExceptions->handleError(8, 'Trying to get property of non-object', 'ThreadController.php', 51, array('request' => object(Request), 'forum_id' => 'soccer', 'forum' => null, 'thread' => object(Thread)))

控制器:

public function create($slug)
{
    //
    $forum = Forum::where('slug', '=', $slug)->first();

    return view('threads.create')->withForum($forum);
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request, $forum_id)
{
    //
    $this->validate($request, array(
        'threadname' => 'required|max:90',
        'post' => 'required|max:99000'
    ));
    $forum = Forum::find($forum_id);
    $thread = new Thread();
    $thread->threadname = $request->threadname;
    $thread->forums()->associate($forum);
    $thread->user_id = $request->user()->id;
    $thread->save();


    return view('forum.index');

}

查看:

{!! Form::open(['route' => ['thread.store', $forum->slug], 'method' => 'POST', 'files' => 'true']) !!}
   {!! Form::label('threadname', 'Title of Thread:') !!}
   {!! Form::text('threadname', null, array('class' => 'form-control')) !!}
  {!! Form::label('post', 'Message:') !!}
  {!! Form::textarea('post', null, array('class' => 'form-control')) !!}
  {!! Form::submit('Create', array('class' => 'btn-send btn-lg btn-block')) !!}
  {!! Form::close() !!}

1 个答案:

答案 0 :(得分:0)

您正在尝试使用字符串soccer查找论坛,这应该是论坛的ID。

'forum_id' => 'soccer'

$forum = Forum::find($forum_id);

如果您使用slug或title搜索,则无法使用find()