Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

Did you try with brackets?

$post->author()

I don't know the exact difference, but there is one. :)

Last updated 2 years ago.
0

d33k4y said:

Did you try with brackets?

$post->author()

I don't know the exact difference, but there is one. :)

If I change my Controller to contain:

$blogPosts = $posts::whereRaw('category = 1 AND status = "published"')->get();

And then add:

@foreach ($blogPosts as $post)
    <h1>{{ $post->title }}</h1>
    <p>{{ $post->content }}</p>
    {{ $post->author()->username }}
    @endforeach

to my view, I get: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$username

Last updated 2 years ago.
0
Model::find($id);

returns single model, not a collection that you'd like to loop through.

Also use with because of this http://laravel.com/docs/eloquent#eager-loading

$posts = Post::take(2)->with('author')->get();

then your code in the view/template will work as expected

Last updated 2 years ago.
0

Something else worth mentioning, why are you instantiating a class just to call a static method?

$posts = new Post;
$blogPosts = $posts::find(2);

You should be doing this instead:

$post = Post::find(2);
Last updated 2 years ago.
0

Is your database column author? If you were intending that database column to be the author's ID number, then you should have named it author_id.

Then, $post->author_id would return the integer, $post->author() would open the relationship object/query, and $post->author would return the User object;

If you can't rename your database column, put this hackish snippet in your post model file:

//    Allows $post->author to return the User object

public function getAuthorAttribute()
{
    return $this->author()->first();
}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

danhardman danhardman Joined 29 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.