2016-04-11 56 views
-1


das ist meine Kommentare Tabelle, wie ich zeigen, so viele Kommentare in Einzel Forum posten

Schema::create('comments', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('post_id')->unsigned(); 
     $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); 
     $table->string('comments'); 
     $table->timestamps(); 
    }); 
} 

diese Tabelle mein Beitrag ist

Schema::create('posts', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('title')->index(); 
     $table->timestamps(); 
    }); 

auf meinem Posten Modell geben i hasMany

public function comments() 
{ 
    return $this->hasMany('App\Comment'); 
} 

auf meine Kommentare Modell ich gebe

public function post() 
{ 
    return $this->belongsTo('App\Post'); 
} 

das ist mein Controller

<?php 

namespace App\Http\Controllers; 

use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Input; 
use App\Http\Requests; 
use App\comment; 
use App\post; 
use Crypt; 


class PostController extends Controller 
{ 
    public function index() { 
     $posts = post::orderBy('created_at', 'desc')->paginate(9); 
     return view('post.index', compact('posts')); 
    } 

public function create(){ 

    return view('post.create'); 
} 

public function store(Request $request){ 

    $post = new post; 
    $post->title = $request->title; 
    $post->save(); 
    return redirect()->route('rules'); 
} 

public function show($title){ 

$post = post::where('title', $title)->first(); 
$comments = post::orderBy('created_at', 'desc')->paginate(10); 

return view('post.show', compact('post', 'comments')); 
} 

public function storecomment(request $request){ 

    $comment = new comment; 
    $comment->post_id = Crypt::decrypt(Input::get('post_id')); 
    $comment->comments = $request->comments; 
    $comment->save(); 

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

i Ansicht foreach haben, aber ich sehe alle Kommentare in jeder schreiben, was ich in meiner Ansicht ein jeder zu zeigen, Kommentare mit post_id

Antwort

0

für immer Kommentare zu Post

@foreach($post as $p) 
    @foreach($p->comments as $comment) 
    {{ $comment->comments }} 
    @endforeach 
@endforeach 
1

erstens entfernen

.
$comments = post::orderBy('created_at', 'desc')->paginate(10); 

von show() Funktion (vergessen Sie nicht 'comments' von compact() zu löschen)

jetzt, fügen Sie diese in Ihrer Ansicht Datei:

@foreach($post->comments->orderBy('created_at', 'desc') as $comment) 
    {{ $comment->title... }} 
@endforeach 
+0

etwas, was noch fehlt i i diesen Fehler Methode orderBy existiert nicht. (Ansicht: E: \ xampp \ htdocs \ neu \ ressourcen \ ansichten \ post \ show.blade.php) –