Laravel Eloquent retrieve the first element and also keep the query result intact?
Asked Answered
A

3

12

Please have a look at the following code:

$msgs = Message::where(function($query) use ($start,$end){

    $query->whereBetween('created_at', array($start, $end));

})->orderBy('created_at', 'DESC');

$first = $msgs->first()->created_at;
$ids = $msgs->lists('id');

What I'm trying to do is to get the latest date of the query result set and get all the ids from the result at the same time. But the code doesn't work because the $msgs was changed by the $msgs->first() function. I'm wondering if there is a way to let me get the first element of the query result without affecting the whole result set? Thanks

Amadaamadas answered 21/5, 2014 at 1:35 Comment(1)
I tried: foreach($msgs as $message) { $first = $message; break; } But it seems it did not go into the foreach at all.Amadaamadas
R
28
$first = $msgs->first(); // this does ->take(1) under the hood

Now your builder has limit = 1 clause.

So basically you need this:

// also you can use pluck:
$first = $msgs->pluck('created_at'); // returns first row`s single field
//then:
$ids = $msgs->take(9999)->lists('id'); // some high value depending on your data

Your solution is not the best, as it loads all the rows and creates objects of them, while all you need is list of ids.

You can also use first() method of the Collection to fetch its first item, instead of that foreach loop:

$messages = $msgs->get();
$first = $msgs->first()->created_at;
Ravenna answered 21/5, 2014 at 13:35 Comment(0)
A
1

I found a solution:

        $msgs = Message::whereBetween('created_at', array($start, $end))                    
                            ->whereIn('advertiser_id', $array)            
                            ->orderBy('created_at', 'DESC');

        $messages = $msgs->get();
        foreach($messages as $message)
        {
            $first = $message->created_at;
            break;
        }               

Surprisingly easy. But I don't know if it's an efficient way or not.

Amadaamadas answered 21/5, 2014 at 2:38 Comment(1)
Know this post is old but why don't you just test if you result is not empty then retrieve the created_at value of the first element of the array like this: $first = $messages[0]->created_at.Fed
D
0

The following should do for laravel 10.x:

$first = $msgs->value('created_at');

This would only return a single value of the first field.

Dygall answered 25/4, 2024 at 6:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.