beginner9191
beginner9191

Reputation: 49

laravel 5.7 Error: Call to a member function save() on null

i'm using Laravel Framework 5.7.25
i'm trying to create a post by current user who has already logged in.
but i'm facing these Errors:

Call to a member function save() on null this is Error: this is my PostController :

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function postCreatePost(Request $request)
    {
        $post = new Post();
        $post->body=$request['body'];
        $request->user()->posts()->save($post);
        return redirect()->route('dashboard');
    }
}

and this is Post model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        $this->belongsTo('App\User');
    }
}

and this is User model

<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements Authenticatable
{
 use \Illuminate\Auth\Authenticatable;
  public function posts()
  {
      $this->hasMany('App\Post');
  }
}

Upvotes: 2

Views: 2330

Answers (2)

ceejayoz
ceejayoz

Reputation: 180004

Your user() and posts() relationships aren't returning anything:

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

needs to become:

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

and the same tweak made for user().

Upvotes: 6

George Hanson
George Hanson

Reputation: 3030

I would change your code slightly, this should work:

class PostController extends Controller
{
    public function postCreatePost(Request $request)
    {
        $request->user()->posts()->create($request->only('body'));

        return redirect()->route('dashboard');
    }
}

Upvotes: 1

Related Questions