John
John

Reputation: 95

laravel 5.2->Fatal error: Call to a member function posts() on null

Help me please. I'm a newbie at laravel 5.2. I dont know why Im getting this kind of error:Fatal error: Call to a member function posts() on null This is my postController file.

<?php
namespace App\Http\Controllers;

use App\post;
use Illuminate\Http\Request;

class postController extends Controller
{
  public function createPost(Request $request)
  {
    //validation..
    $post= new Post();
    $post->body= $request['body'];
    $request->user()->posts()->save($post);

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

this is my Post.php file

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

my User.php file

<?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()
    {
        return $this->hasMany('App\post');
    }
}

Thanks in advance.

Upvotes: 1

Views: 3260

Answers (1)

Jed
Jed

Reputation: 1074

Is it possible that you are not logged in yet of your application that's why when you called:

$request->user()->posts()->save($post);

user() is still null so there will be no reference to the posts() relation?

EDIT:

To check whether you are logged in you can say:

if(Auth::user()){
 //do something here...
}

Also I don't think you should save your Post like that. If you want to add the user_id on your post you can say:

$post->user()->associate(Auth::user());
$post->save();

Upvotes: 6

Related Questions