jebeeee
jebeeee

Reputation: 51

Call to a member function create() on null - laravel

I would like to create a post using the current user in Auth. But i have my error.

Thank you!

Controller

public function publish(Post $post){
    $this->validate(request(), [
                'title' => 'required',
                'body'  => 'required'
            ]);


            auth()->user()->publish(
                new Post(request(['title','body']))
            );
        }

User model:

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


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

Error Call to a member function save() on null

Upvotes: 2

Views: 2141

Answers (1)

Hollings
Hollings

Reputation: 532

Laravel relationships should return the relationship, like this:

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

Upvotes: 4

Related Questions