Can someone tell me what to do in this error. The error is in this line. 'posts' => $author->posts->load('category', 'author')
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->posts->load('category', 'author'),
]);
});
this is my controller
class PostController extends Controller
{
public function index()
{
return view('frontend.posts', [
"title" => "All Posts",
// "posts" => Post::all()
"posts" => Post::latest()->get()
]);
}
public function show(Post $post)
{
return view('frontend.post', [
"title" => "Single Post",
"post" => $post
]);
}
}
this is my models
class Post extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $with = ['category', 'author'];
public function category(){
return $this->belongsTo(Category::class);
}
public function author(){
return $this->belongsTo(User::class, 'user_id');
}
}
and this is my user models
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
public function post(){
return $this->hasMany(Post::class);
}
}
I have this previous error to "foreach() argument must be of type array|object, null given". I want to display blog posts from certain users. This is the code from posts.blade.php.
@foreach ($posts as $post)
<div >
<h4 >
<a href="/posts/{{ $post->slug }}"
>
{{ $post->title }}
</a>
</h4>
<p >
{{ $post->excerpt }}
</p>
<div >
<span >
<span>
<span >By</span> <a href="/authors/{{ $post->author->username }}">{{ $post->author->name }}</a>
<span >|</span>
</span>
<span>
<a href="/categories/{{ $post->category->slug }}">{{ $post->category->name }}</a>
<span >|</span>
</span>
<span>
8 Comments
</span>
</span>
<a href="/posts/{{ $post->slug }}" >
Continue Reading
<i ></i>
</a>
</div>
</div>
@endforeach
CodePudding user response:
The name of the relationship in User
is post
but in your controller you used posts
.
The following should probably work:
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->load('post.category'),
]);
});