Rainier laan
Rainier laan

Reputation: 1130

Laravel show latest post on homepage

I'm trying to display the latest post, posted on my website. I have a vague idea of how it needs to be done but I'm not 100% sure. I think I need to do something like this in my PostController.php

public function index()
 {
    $laatstepost = Post::orderBy('created_at', 'desc')->take(1)->get();

    return View('showposts')->with('laatsteposts', $laatstepost);
 }

And then something like this in my view.

<div class="panel-body">
  <h3>{{ $laatsteposts->title }}</h3>
       <p>{{ $laatsteposts->text}}</p>
       <a href="{{ Link to latest post}}" class="post-read-more">Lees meer...</a>
 </div>

I don't know if I'm heading the right way or that I'm completely off track. If u guys can help me out that would be great! Thanks

Here is a screenshot of where it needs to be displayed: https://i.sstatic.net/5vWz9.jpg

If I miss code that is needed for this, Tell me

Upvotes: 2

Views: 2871

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163918

Use the first() method to get an object instead of collection:

public function index()
{
   $laatstepost = Post::latest()->first();

   return view('showposts')->with('laatsteposts', $laatstepost);
}

And in the view:

<div class="panel-body">
    <h3>{{ $laatsteposts->title }}</h3>
    <p>{{ $laatsteposts->text }}</p>
    <a href="{{ Link to latest post}}" class="post-read-more">Lees meer...</a>
</div>

Alternatively, you can use your code to get a collection with just one element and display data in the view using first() collection method:

<div class="panel-body">
    <h3>{{ $laatsteposts->first()->title }}</h3>
    <p>{{ $laatsteposts->first()->text }}</p>
    <a href="{{ Link to latest post}}" class="post-read-more">Lees meer...</a>
</div>

Upvotes: 1

Related Questions