0

Hey I want to make a relation between my posts table and my categorie table. But I can't get it working.

Here's my code:

Posts.php (model)

<?php
class Post extends Eloquent
{
    protected $table = "posts";

    public function categorie()
    {
        return $this->BelongsTo('Categorie');
    }
}

..

Categorie.php (model)

<?php
class Categorie extends Eloquent
{
    protected $table = "categories";

    public function posts()
    {
        return $this->hasMany('Post');
    }
}

..

PageController.php (controller)

<?php
class PageController extends BaseController
{
    public function getIndex()
    {
        $posts = Post::all();
        return View::make('layout.index')->with('posts', $posts);
    }
}

How can I show all my posts now with the categories they belong to? I know if I do $post = Post::find(1)->categorie it returns the categorie that belongs to post id 1 but I want to return all my posts with the categorie

1 Answer 1

1

You need to load the relationship when you call in all the posts.

$posts = Post::with('categorie')->get();

Also, the method is belongsTo not BelongsTo.

Also, just a side note. The singular is category and the plural is categories. I'd have my model called Category and the relationship called category.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.