A
A
Alexander2019-05-28 03:07:44
Laravel
Alexander, 2019-05-28 03:07:44

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

1 answer(s)
L
Lander, 2019-05-28
@Sentim

as

foreach ($items as $rubric) {
    $rubric->news->map(function ($post) {
        echo $post->title;
        //Ну и остальные поля новости. Какие они там у вас.
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question