Naveen Kumar
Naveen Kumar

Reputation: 1626

call to a member function on null Laravel 5.2

I am creating something more like a facebook post , i get a post from user and store it to database for now. I have created two models User and Post

here is the code of User model

    <?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Eloquent implements Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


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

Here is the code of Post model

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()

    {

        return $this->belongsTo('App\User');
    }
}

and I have a postController and here is the code of it

    use App\Post;

use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Illuminate\Contracts\Auth\User;
use App\Http\Controllers\Controller;

class PostController extends Controller
{

    public function createPost(Request $request)
    {

        $post = new Post();

        $post->userpost = $request['userpost'];
        $request->user()->posts()->save($post);  -> **Error here Call to a member function posts() on null**
        return redirect()->back();

    }}

Upvotes: 1

Views: 60591

Answers (2)

MrCode
MrCode

Reputation: 64536

The error is indicating that $request->user() returned null, which means that the user is not logged in to the application – i.e is a guest. The method $request->user() will only return a user, if a user is authenticated.

From the documentation:

once a user is authenticated, you may access the authenticated user via an Illuminate\Http\Request instance

The solution is to wrap your code in an auth check like below, or use middleware to prevent access to this route unless the user is authenticated.

if(\Auth::check()){
    $post = new Post();

    $post->userpost = $request['userpost'];
    $request->user()->posts()->save($post);
} else {
    // not logged in - do something
}

Upvotes: 5

Prashant G Patil
Prashant G Patil

Reputation: 977

use App\Post;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Illuminate\Contracts\Auth\User;
use App\Http\Controllers\Controller;

class PostController extends Controller
{

  public function createPost(Request $request)
    {

    $post = new Post();
    $post->userpost = $request['userpost'];
    $post->user_id = LOGGED_IN_USER_ID; 
    //$request->user()->posts()->save($post);
    $post->save();
    return redirect()->back();
    }
}

Upvotes: 1

Related Questions