Here's my answer using Laravel 8 and belongsTo
.
In my solution, I created first the relationship User and Post
// Post migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title',160)->unique();
$table->string('image');
$table->text('content')->nullable();
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
In My Post model I created the authors function
// Post Model
public function authors()
{
return $this->belongsTo(User::class, 'user_id','id');
}
Where the 'user_id' is the foreignKey, and id is ownerKey
Now I Call Post model in my controller using this
//Post Controller
//return latest posts with the author and paginate it
public function index()
{
$posts = Post::latest()->with('authors')->paginate(3);
return view('blog',compact('posts'));
}
And finally, I use it in blog.blade file
//blog.blade
<hr>
@foreach ($posts as $post)
<h3>{{$post->title}}</h3><pre>{{$post->role}}</pre>
//get author name forech post
<pre>{{$post->authors['name']}}</pre>
@endforeach
<hr>