Question

I have a Score-Table with different ratings, strings and radio-buttons.

Now I want to loop through these. Normally I would go about solving it like this:

 <table>
    <tr>
        <th>ID</th>
        <th>Type</th>
        <th>Comment</th>
    </tr>
    @foreach($scores as $score)

    <tr>
        <td>{{$score->id}}</td>
        <td>{{$score->ratingradio}}</td>
        <td>{{$score->ratingtext}}</td>
    </tr>

    @endforeach
</table>

But I don't only want the order to be reversed, but I also want the array to be sliced, so that it just outputs the last 20 Elements of the array.

I attempted solving it like this in my Controller:

$scores = Score::where('unit_id', $id)->where('created_at', '>', Carbon::now()->subDays(3))->get();


// Save all ratingtexts in an array
$comments = $scores->lists('ratingtext');
$commenttype = $scores->lists('ratingradio');
// Get the last 20 Elements of the Array
$comments = array_slice($comments, -20, 20, true);
// Reverse the array, to have the latest element first displayed
$comments = array_reverse($comments, true);

And then looping through the $comments. But I don't only want to display the comment, I also want to be able to display all Information regarding this Element. So preferably like the above method with eloquent, where I output $score->ratingtext, $score->ratingradio, $score-id, and whatever I want.

I tried just using

 @foreach(array_reverse($scores) as $score)

Which obviously didn't work, because $scores is an object and it was expecting an array. How am I going to reverse loop through every score of my Scores Table?

Was it helpful?

Solution

Retrieving the last 20 items is quite easy.

$scores = Score::where('unit_id', $id)
    ->where('created_at', '>', Carbon::now()->subDays(3))
    ->orderBy('created_at', 'desc')
    ->take(20)
    ->get();

$scores = $scores->reverse();

Done.

Just tell it to pull out the first 20 items that match your query, with a reversed order and then reverse the collection to get the proper order.

OTHER TIPS

You can as well easily do @foreach($scores->reverse() as $score)

You can use:

array_reverse($scores->toArray());

or Eloquent\Collection methods to keep the Model object

$scores->reverse();

Take a look at the Eloquent\Collection API.

There are even easyest way:

$scores = Score::where('unit_id', $id)
    ->where('created_at', '>', Carbon::now()->subDays(3))
    ->orderBy('created_at', 'desc')
    ->orderBy('id', 'asc')
    ->take(20)
    ->get();

Looking through the API, it seems you can use take() to make this very simple. It behaves a little differently when running on query builder vs collection, so you'd want to get your collection first.

$scores = Score::where('unit_id', $id)->where('created_at', '>', Carbon::now()->subDays(3))->get()->take(-20);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top