Reputation: 79
I am pretty new to Laravel and i have been stuck with this problem for quite a while now ,I face a problem when trying to get a user name through post table using hasMany relationship. Hope the added code helps to understand the problem better. Thank you
public function main_page(){
$post= Post::all();
return view('main' , compact('post') );
}
@extends('layouts.app')
@section('content')
@foreach ($post as $p)
{{$p->users()->name }}
@endforeach
@endsection
public function users(){
$this->belongsTo('App\User');
}
I expect that author's name of the post would be displayed ,but it is not the case. I get an error:
Trying to get property 'name' of non-object
My posts table looks like this:
id
user_id
title
content
created_at
updated_at
Upvotes: 1
Views: 490
Reputation: 349
try
Blade view
@foreach ($post as $p)
{{$p->user->name }}
@endforeach
Controller
public function main_page(){
$post= Post::with('user')->latest()->get();
return view('main' , compact('post') );
}
Model post
public function user(){
$this->belongsTo('App\User');
}
Upvotes: 0
Reputation: 2636
You're not returning the user in the relation in your Post model, try this:
public function user(){
return $this->belongsTo('App\User');
}
The name of the function should be user
, on singular as @Ross Wilson suggested.
In your view you could do this:
@section('content')
@foreach ($post as $p)
{{$p->user->name }}
@endforeach
@endsection
Upvotes: 0
Reputation: 35180
You were close.
{{ $p->users->name }}
If you don't want to add clauses to your relationships then you can access it by treating it as a property.
I would suggest renaming your users()
method to user()
as a belongsTo
relationship with will only ever return a single model. If you do that then you'll need to change the code in your blade file to $p->user->name
.
Upvotes: 1