我要做的是能够将表单中的评论发布到帖子中。我知道我模特的名字很糟糕。它应该被称为post而不是dummy。当我调用我为评论表制作的新控制器时,我收到了这个错误。此外,我在虚拟模型中创建了一个新函数,因此我的代码可以更加整洁有序。在我在虚拟模型中创建新函数之前和调用不同的控制器之前,我能够发表评论。以下是我认为错误所在的文件:
这是路线:
Route::post('post/{post}/comments', 'commentController@store');
这是虚拟模型应该被称为post并且我为它创建了新函数,以便在commentController文件中缩短代码:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class dummy extends Model
{
protected $guarded = [];
public function comments(){
return $this->hasMany(Comments::class, 'post_id');
}
public function addComment($body){
$this->comments()->create(compact('body'));
}
}
最后这里是commentController文件:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; //this one is for sql builders
use App\Dummy;
use App\Comments;
use Illuminate\Http\RedirectResponse;
use DateTime; //to create a new date object yo need to include this namespace
class commentController extends Controller
{
public function store(Dummy $post){
$date = new DateTime();
$timestamp = $date->getTimestamp();
$id = $post->id;
$post->addComment(request('body'));
return view('post', compact('post', 'timestamp', 'id'));
}
}