调用null Laravel 5.2上的成员函数

时间:2016-06-01 08:45:18

标签: php laravel laravel-5.2

我正在创建更像facebook帖子的东西,我从用户那里得到一个帖子,现在将它存储到数据库中。我创建了两个模型用户和帖子

这是用户模型的代码

jquery-ui.css

这是Post模型的代码

    <?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');
    }
}

我有一个postController,这里是它的代码

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()

    {

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

2 个答案:

答案 0 :(得分:2)

错误表明$request->user()返回null,这意味着用户未登录到应用程序 - 即访客。如果用户通过身份验证,方法$request->user()将仅返回用户。

来自documentation

  

用户通过身份验证后,您可以通过Illuminate \ Http \ Request实例访问经过身份验证的用户

解决方案是将代码包装在如下所示的身份验证检查中,或者使用中间件来阻止访问此路由,除非用户经过身份验证。

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

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

答案 1 :(得分:1)

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