dimanche 28 février 2016

Eloquent relationship with several models

I'm new to Laravel and I've been watching the Laracast videos but I didn't understand the Defining Relationships With Eloquent. Then, I moved to the official documentation to understand a little bit more, and by following their examples, I could make something work.

I'm building a small blog website using Laravel 5.2, and I already have few tables in my database. They are users, posts, categories, comments and likes.

So far, I've build a Post and Comment model. Post hasMany Comment, while Comment belongsTo Post, and following the documentation's examples, I've made the following in my controller, in order to show the comments of that specific Post:

public function show($id)
{
    return \View::make('admin/post/show')->with(array(
        'post' => \DB::table('posts')->find($id),
        'comments' => \App\Post::find($id)->comments
    ));
}

And showed in the show.blade.php view like this:

<div class="row">
    @foreach ($comments as $comment)
        {{ $comment->comment }}
    @endforeach
</div>

Is this way of doing it correct? I need also to show the User's name along with the Comment. Also, about the Like model, I will eventually need to show the User's name and the Post's title. Is there a better way of how I just did for these needs, with more than two related models?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1OGzwJv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire