Reputation: 79
I'm trying to write this code in laravel controller.
$messages = $db->query("
SELECT name, message
FROM messages
ORDER BY created ASC
LIMIT 100
");
header('Content-Type: application/json');
echo json_encode(
$messages->fetchAll(PDO::FETCH_OBJ)
);
but I can't write the ->fetchAll(PDO::FETCH_OBJ)
Upvotes: 1
Views: 359
Reputation: 2556
if you create a Message model class, you can simply call:
$messages = Message::latest('created', 'asc')->paginate(100, ['name', 'message']);
return response()->json($messages);
Upvotes: 1
Reputation: 21
If you are using Laravel, you might want to be using Eloquent to achieve this, however if you don't want to do that I'm going to assume you'll be using the Illuminate query builder.
Your query can be replicated as follows:
$messages = DB::table('messages')
->select('name', 'messages')
->orderBy('created', 'asc')
->take(100)
->get();
which you can then json_encode
as you are.
Upvotes: 1