Did you try with brackets?
$post->author()
I don't know the exact difference, but there is one. :)
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
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
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);
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();
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community