John Evans Solachuk
John Evans Solachuk

Reputation: 2085

use eloquent ORM to get data from database

I have an array of timestamps and I want to compare it with the ones in a table. This is my code in my controller :

public function create(){

    $from = Input::get('from'); //array of timestamps of current messages displayed
    $conv_id = Input::get('conv_id'); //array of ids

    //get all messages related to the array of ids
    $allMessages = Messages::whereIn('conv_id',$conv_id);

    //get the messages in database which have timestamps greater than the current ones displayed.
    $messages = $allMessages->where('created_at','>',$from);

    return $messages->get()->reverse();
}

This works for a single timestamp passed. However, if it was an array of timestamps that was passed, Laravel was not able to detect the latest messages. I have tried,

$messages = $allMessages->whereIn('created_at','>',$from);

But it returns an Array To String conversion error. I suspect I might be using it wrongly.

So I repeat, how do I get all messages in the table which have timestamps greater than the timestamps that I got from the Input class?

I think this can be done using PHP's explode() but I want to keep my codes as 'Laravel-ish' as possible. If explode() is unavoidable, please show me how to use it. Btw, bonus impression points for improvement of code! Thank you!

P.s. This is the result of dd($from) :

array (size=2)  0 => string '2014-06-18 06:53:45' (length=19)  1 => string '2014-06-18 14:52:29' (length=19)

Upvotes: 1

Views: 830

Answers (1)

Joe
Joe

Reputation: 1394

You need exactly what you have, but to find the latest date in the array and use that.

This can be done easily

$from = array('2014-06-18 09:10:32', '2014-06-17 10:52:25'); // Input::get('from');
$conv_id = Input::get('conv_id');

asort($from); // Sort the array of dates in order of earliest date first.

$messages = Messages::whereIn('conv_id', $conv_id)->where('created_at', '>', end($from))->get();

This will return all messages where the created_at timestamp is greater than the latest date in the $from array.

Upvotes: 3

Related Questions