简体   繁体   中英

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();

    }}

The error is indicating that $request->user() returned null , which means that the user is not logged in to the application – ie 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
}
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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM