[英]Laravel: Error trying to get unique users to create posts
正確,因此我試圖建立一個注冊用戶可以創建帖子的網站。 我現在遇到的問題是將帖子添加到數據庫中。 它應該可以工作,但是即時通訊出現錯誤。
錯誤:
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>
問題是您在控制器上執行以下操作:
$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');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.