manshu
manshu

Reputation: 1105

Error storing Topic Model into the database using Sentinel

I have a small forum, im trying to create topic and replies for the store method.

routes.php

Route::get('board/{id}/create', 'TopicsController@create');
Route::post('board/{id}/create', 'TopicsController@store');

TopicsController.php

public function store()
{
    $this->request->user()->topics()->create([
        'board_id' => $this->request->id,
        'title' => $this->request->title,
        'body' => $this->request->body
    ]);
    return redirect(url('/board/' . $this->request->id));
}

I am receiving this error.

Call to a member function topics() on null

Also note, i am using Sentinel https://github.com/rydurham/Sentinel from this repo.

<?php namespace App\Models;


class User extends \Sentinel\Models\User
{

    protected $fillable = ['email', 'first_name', 'last_name'];

    protected $hidden = ['password'];

    public function topics()
    {
        return $this->hasMany(Topic::class);
    }

    public function replies()
    {
        return $this->hasMany(Reply::class);
    }

    public function getGravatarAttribute()
    {
        $hash = md5(strtolower(trim($this->attributes['email'])));
        return "https://www.gravatar.com/avatar/$hash";
    }
}

Updated Model

public function store($id)
    {
        $user = Sentry::getUser($id);

        $user->topics()->create([
            'board_id' => $this->request->id,
            'title' => $this->request->title,
            'body' => $this->request->body
        ]);
        return redirect(url('/board/' . $this->request->id));
    }

Upvotes: 0

Views: 52

Answers (1)

geckob
geckob

Reputation: 8128

It seems that your user object is null. Properly retrieve the user using the id

public function store($id)
{

    $user = \App\Models\User::find(\Sentinel::getUser()->id);

    $user->topics()->create([
        'board_id' => $this->request->id,
        'title' => $this->request->title,
        'body' => $this->request->body
    ]);
    return redirect(url('/board/' . $this->request->id));
}

Upvotes: 1

Related Questions