vendredi 13 avril 2018

Trying to get property of non-object issue with associating

I'm trying to post a new thread in one of my forums through a create and store form and keep encountering an error when trying to associate the thread with the forum i'm posting the thread inside. Anyone know where the issue is?

issue:

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)))

Tables: Forum: id, name, slug, timestamps Threads: id, name, forum_id, user_id, timestamps

Models:

public function forums(){
    return $this->belongsTo('App\Forum', 'forum_id');
}

Controller:

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();
    $forumpost = new Forumpost();
    $forumpost->post = $request->post;
    $forumpost->threads()->associate($thread);
    $forumpost->user_id = $request->user()->id;
    $forumpost->save();

    return view('forum.index');

}

View:

{!! 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() !!}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire