Laravel:尝试让独特用户创建帖子时出错

时间:2018-04-11 16:06:02

标签: php laravel

是的,所以我试图建立一个注册用户可以创建帖子的网站。我现在遇到的问题是将帖子添加到数据库中。它应该工作,但我得到一个错误。

错误:

 Call to a member function posts() on null

错误指向我的帖子控制器类

<?php

use App\Post;
namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

这是我的迁移后升级方法:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->text('body');
        $table->integer('user_id');
    });
}

发布模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

用户模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;

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

用户输入的部分:

<section class="row new-post">
    <div class="col-md-6 col-md-offset-3">
        <form action="{{ route('postcreate') }}" method="post">
            <div class="form-group">
                <textarea class="form-control" name="body" rows="5" placeholder="your post"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Create post</button>
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
        </form>
    </div>
</section>

1 个答案:

答案 0 :(得分:0)

问题在于您在控制器上执行以下操作:

$request->user()->posts($post); //points here

您正在考虑user()将始终返回一些内容。

如果您的路由未被auth中间件保护,$request->user()可能会返回null,如果没有经过身份验证的用户。

所以你有两个选择:或者你添加auth中间件,或者在你的代码上添加一个if:

if ($request->user()) {
    $request->user()->posts($post);
}

然而,这将解决错误,但它不会创建帖子

public function postCreatePost(Request $request){
    $post = new Post(); 
    $post->body = $request['body'];
    $request->user()->posts($post); // This call isn't valid.
    return redirect()->route('dashboard');
}

正确的方法是:

public function postCreatePost(Request $request){
    $request->user()->posts()->create([
        'body' => $request->body
        // Here I'm assumming that the only field is the `body`,
        // but you may need other fields if they exists.
        // the `user_id` field will be automatically filled.
    ];

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