K
K
Konstantin2017-07-07 20:42:43
Laravel
Konstantin, 2017-07-07 20:42:43

How to display several previews (in different blocks) of articles from different categories on one page in Laravel?

Good evening!
I will try to explain a little: I
reviewed a number of videos and articles on the topic of creating a blog on Larevel (5) and everywhere, as a rule, they show how to display an article on the main page and make a link to go to the full version of the page, but I need to place it on the main page previews of several pages, say, in two blocks (let's say 5 previews in each of the two blocks, each block has its own category), i.e. the database has an article table (which will contain all the articles), an Article model, and an ArticlesController controller. I haven’t figured out the categories themselves yet, but I can filter the output in the page block (using the category_id field in the table), but it’s not clear how to display articles from different categories in different blocks (the blocks are in the same view)(and in the end there will be about 10 blocks, i.e. categories). I would be grateful if someone tells me in which direction to move, maybe some code example will be thrown off on the topic. The templating engine used is blade.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2017-07-08
@vkn

1. Linking category and article models ( documentation )

class ArticleCategory extends Model
{
...
    public function articles()
    {
        return  $this->hasMany('App\Article', 'category_id');
    }
...

2. In the controller, we get a list of all categories along with their articles:
3. In the view, we go through all the categories and display the posts of each in separate blocks:
@foreach($categories as $categorie)
    <div class="category_block">
       <h3>{{ $categorie->name }}</h3>
       @foreach($categorie->articles as $article)
           <div class="article">
               {{ $article->name }}
           </div>
       @endforeach
    </div>
@endforeach

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question