1

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)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

if you create a Message model class, you can simply call:

$messages = Message::latest('created', 'asc')->paginate(100, ['name', 'message']);

return response()->json($messages);

1 Comment

Should note that $messages->links() contains your paginated links as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.