DEV Community

Code And Deploy
Code And Deploy

Posted on

Building Laravel 8 Eloquent Query Example

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/building-laravel-8-eloquent-query-example

In this post, I will share an example for Laravel Eloquent Query. The Laravel Eloquent all() method will retrieve all results in the model's table. But since each Eloquent model serves as a query builder, you can add additional constraints to your queries and invoke the method get() to retrieve the results.

When doing a simple query to get all records from a table using MySQL your statement:

SELECT * FROM posts
Enter fullscreen mode Exit fullscreen mode

But if we use an eloquent query then we will just use all() methods:

$posts = Post::all();
Enter fullscreen mode Exit fullscreen mode

Applying query builder methods to our Laravel eloquent query:

$posts = Post::where('status', 1)
               ->orderBy('title')
               ->take(10)
               ->get();
Enter fullscreen mode Exit fullscreen mode

That's it, now you have the basics on how to use Laravel 8 eloquent queries.

For more methods about query builder just visit the full documentation.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/building-laravel-8-eloquent-query-example if you want to download this code.

Happy coding :)

Top comments (0)