Brij Sharma
Brij Sharma

Reputation: 371

How to fetch username from other table user_id store in other table

I have a table "articles" in this table a column name "user_id", I have another table "users" where store username, profile_pic etc... I want to fetch username on home page where I already fetched articles title.

Article Model

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
    public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }
}

View Page(Home Page)

{{$article->user_id}}

Here I want to Display username

User Model

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Upvotes: 1

Views: 50

Answers (1)

GTMeteor
GTMeteor

Reputation: 857

Add the following to Article class:

public function user() {
    return $this->belongsTo(User::class);
}

Then you can access related user data with $article->user->name

Upvotes: 1

Related Questions