Fluxify
Fluxify

Reputation: 145

Laravel Eloquent Model Relationships fetching

I am new to laravel, I have articles and Users table. How do i fetch who's user created a specific article

All articles

  1. Article 1 by John Doe
  2. Article 3 by Jane Doe.

Upvotes: 0

Views: 36

Answers (2)

Filip Koblański
Filip Koblański

Reputation: 10018

You need to add a relation method to your Article model:

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

Then you can access to this user by a magic method with the property of user like this:

{{ $article->user->email }}

Upvotes: 0

Amir Bar
Amir Bar

Reputation: 3105

Take a look at relationships docs:

$article = Article::where('id','=',10)->with('user')->first();

echo "article {$article->id} by {$article->user->name}";

Upvotes: 1

Related Questions