v2.5.2
Giriş yap

Slug üzerinden post id bulma ve yazdırma

goxaria
333 defa görüntülendi

Benim post ve comment olmak üzere iki ayrı tablom var
Post tablomun sütunları id, title, slug
Comment tablomun sütunları id post_id, body

Ben tek formda postumun idsi ile commentin bodysini birleştirip gönderiyorum. Ancak benim slug'ım ve title'ım unique olmalı. Bu yüzden de daha önceden oluşturulmuş bir title ve slug var ise postumdan id title slug göndermeyi bırakıp o idi bulup sadece comment ile post ettirmek istiyorum. İlk gönderi olduğu için hidden ile post id gönderemem çünkü insanların ne slug değeri göndereceğini bilmiyorum. Gönderilen slug değerinden id'i bulmam gerekiyor.

if (Post::where('slug', '=', $slug)->exists()) {

    // Burada post id'yi nasıl bulacağımı çözemedim
    $post_id = $post->id;
    
    $comment = new Comment;
    $comment->post_id = $post_id;
    $comment->body = $request->body;
    $comment->user_id = auth()->user()->id;
    $comment->save();

} else {

    $post = new Post;
    $post->title = $request->title;
    $post->slug = $slug;
    $post->save();

    $post_id = $post->id;

    $comment = new Comment;
    $comment->post_id = $post_id;
    $comment->body = $request->body;
    $comment->user_id = auth()->user()->id;
    $comment->save();
Cevap yaz
Cevaplar (1)
isa
819 gün önce
//Get etme fonksiyonun neyse exists yerine onu yaz...
$post = Post::where('slug', '=', $slug)->exists();
if(is_null($post)){

    Yeni post oluştur ve save et,

}else {

    $comment = new Comment;
    $comment->post_id = $post->id;
    $comment->body = $request->body;
    $comment->user_id = auth()->user()->id;
    $comment->save();
}