简体   繁体   中英

how to use count in for each in laravel

  <h3>Top Members</h3>
    <div class ="name">
    <div class="col-md-2" id="content">
    <?php $i=0; ?>
    @foreach($posts as $post)
    <h5><a href="#"<i class="glyphicon glyphicon-user"></i></a>{{ $post->user->name }} </h5>
    @endforeach

Here is my code , I want to select top 5 from database

In you controller where you get the $posts var instead of

Post::orderBy('created_at','asc')->get();

use something like

Post::orderBy('created_at','asc')->take(5)->get();

NOTE: thi is only an assumtion how you call your posts

你可以这样使用

Post::all()->take(5)->get();

You can get count of number of records in table using model

$count = ModelName::count();

For top 5 records

ModelName::all()->take(5)->get();

For paginatation

$data= ModelName::paginate(15);
Fetch the 5 rows from the database by writing the select query with limit and then loop those columns in view page.

In Controller:

public function post_lists(){
$posts=\DB::table('posts_table')->limit(5)->orderby('postid','desc')->get();
return view('posts', compact('posts'));
}

In View page:

<h3>Top Members</h3>
    <div class ="name">
    <div class="col-md-2" id="content">
    <?php $i=0; ?>
    @foreach($posts as $post)
    <h5><a href="#"<i class="glyphicon glyphicon-user"></i></a>{{ $post->user->name }} </h5>
    @endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM