Answer the question
In order to leave comments, you need to log in
How to display data from linked table in Laravel?
Good afternoon. Can you tell me how to display category entries that are in the linked table? Perhaps I went the wrong way, and therefore I would like to know: how is the approach of displaying data from two related tables correctly implemented?
//модель рубрик
class Rubric extends Model
{
protected $table = 'rubric';
public function news ()
{
return $this->belongsToMany('App\News', 'news_to_rubric', 'rubric_id', 'article_id', 'id' );
}
}
//модель новостей
class News extends Model
{
protected $table = 'news';
public function user ()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
}
//Контроллер
class TestController extends Controller
{
public function index ()
{
$items = Rubric::all();
foreach ($items as $item){
$item->news;
}
return view('test', ['items' => $items]);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question