1
votes

I have "posts" table that has many-to-one relationship with "categories" table. The goal is to show all of posts and their categories.

Tables:
Posts: id, content, category_id, etc
Categories: id,name

Here's my code

Models:

class Posts extends Eloquent
{
    public static $table = 'posts';

    public function categories()
    {
        return $this->belongs_to('Categories');
    }
}

class Categories extends Eloquent
{
    public static $table = 'categories';

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

My controller

public function get_posts()
{
    $posts = Posts::with('categories')->all();

    return View::make('admin.posts')
        ->with('title', 'Posts')
        ->with('posts', $posts);

}

My view

@foreach($posts as $post)
        <tr>
            <td>{{ $post->title }}</td>
            <td>{{ $post->categories->name }}</td>
            <td><small> {{$post->updated_at}} </small></td>
            <td>
                <button>
                    {{HTML::link_to_route('edit_post','Edit',array($post->id))}}
                </button>
                {{Form::open('admin/delete','Delete')}}
                {{Form::hidden('id', $post->id)}}
                <input type="submit" name="edit_post" value="Delete"/>
                {{Form::close()}}
            </td>
        </tr>
@endforeach

ERROR:

Error rendering view: [admin.posts]
Trying to get property of non-object

I am a newbie, please help me solve this issues

4

4 Answers

2
votes

{{ $post->categories->name }} before test is categories exists

Example:

@if( ! empty($post->categories))
    <td>{{ $post->categories->name }}</td> 
@else

@end if

Aesis.

0
votes

Just use ::all() instead of ::with(..)->all()

0
votes

categories is an array as you are using a has_many relationship. There are many categories, hence an array is returned, so to access it you have to index it like an array

the correct solution would be

$post->categories[0]->name

0
votes

Are you using Laravel 4? First the syntax for declaring relationship is hasMany and belongsTo, in camel case. Check it out in Laravel documentation

In view, check if categories are empty collection, ie., whether post has its category:

@if($post->categories->count())
    <td>{{ $post->categories->name }}</td>
    ...
@endif

By the way, I would use singular form as model class name, like Post and Category instead of plural forms. And in Post class I would define inverse one-to-many relationship with singular form, to show there's only one entry in category table for this given Post.

public function category()
    {
        return $this->belongsTo('Category');
    }