Question :
I have two tables that are already related in MySQL
and I use Laravel
, I’m already persisting the information in the database. When I write a story, it is already assigned to the author (tables autor
and news
).
At the time of listing news
, I did the following method on NewsControllers
public function listar()
{
$news= News::all();
return view('listar')->with('news', $news);
}
Then when I want to display them in views, I do
@foreach ($news $n)
<tr>
<td>{{ $n->id}}</td>
<td>{{ $n->conteudo}}</td>
</tr>
@endforeach
And it works perfectly.
My question would be, how do I display the author’s name in that listing and in that list method?
[news]
id
titulo
conteudo
autor (FK com id de autores)
[authors]
id
nome
Answer :
This also works:
public function listar()
{
$news= News::join('autor', 'news.autor', '=', 'autor.id')
->select('news.id', 'titulo', 'conteudo', 'nome')
->get();
return view('listar')->with('news', $news);
}
To use all features of Eloquent
you should add the relationships as follows:
<?php namespace App;
use IlluminateDatabaseEloquentModel;
class News extends Model
{
protected $table = 'news';
public $timestamps = true;
public function autor()
{
return $this->belongsTo('AppAutores', 'autor', 'id');
}
}
In the controller
method call the relation with with
:
public function listar()
{
$news= News::with('autor')->get();
return view('listar')->with('news', $news);
}
And in your view
:
@foreach ($news as $n)
<tr>
<td>{{$n->id}}</td>
<td>{{$n->conteudo}}</td>
<td>{{$n->autor->nome}}</td>
</tr>
@endforeach