nie umiem poprawnie dodac "post_id" w tabeli "comments". (funkcja "dodaj"). laravel 8 livewire.
public function dodaj()
{
$this->validate(['nowy' => 'required|max:255']);
$user_id= $this->user_id=Auth::user()->id;
$post_id = ????????????????????????????????????????????????????
$createdKom = Comment::create([
'body' => $this->nowy,
'user_id' =>$this->user_id,
'post_id'=>$this->post_id,
]);
$this->nowy = '';
session()->flash('message', 'Comment added successfully ');
}
class Post extends Model
{
use HasFactory;
protected $fillable =['body', 'user_id', 'image'];
protected $guarded = [];
public function user(){
return $this->belongsTo('App\Models\User', 'user_id');
}
public function comments(){
return $this->hasMany('App\Models\Comment', 'post_id');
}
public function getImagePathAttribute()
{
return Storage::disk('public')->url($this->image);
}
}
class Comment extends Model
{
use HasFactory;
protected $fillable =['body', 'user_id', 'post_id', 'image' ];
protected $guarded = [];
public function user(){
return $this->belongsTo('App\Models\User', 'user_id');
}
public function post(){
return $this->belongsTo('App\Models\Post', 'post_id');
}
public function getImagePathAttribute()
{
return Storage::disk('public')->url($this->image);
}
}
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->text('body');
$table->string('image')->nullable();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('post_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
}
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->text('body');
$table->string('image')->nullable();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}