Laravel's Eloquent ORM, you can limit the number of results returned by a query using the `limit()` method. This is useful when you want to retrieve only a specific number of records from the database.
Basic Usage of `limit()`
The `limit()` method restricts the number of rows returned by the query. Here's an example:$users = User::limit(5)->get();This query will return only 5 records from the `users` table. Example with Query Suppose you want to fetch the latest 5 users from the `users` table:
$latestUsers = User::orderBy('created_at', 'desc') ->limit(5) ->get();-> `orderBy('created_at', 'desc')`: Orders the results by the `created_at` column in descending order (newest first). -> `limit(5)`: Limits the results to 5 records.
Combining `limit()` with Other Methods
You can combine `limit()` with other Eloquent methods like `where()`, `orderBy()`, etc. For example://asc orderby $activeUsers = User::where('status', 'active') ->orderBy('name', 'asc') ->limit(10) ->get(); //desc orderby $activeUsers = User::where('status', 'active') ->orderBy('name', 'desc') ->limit(10) ->get();This query retrieves the first 10 active users, ordered by their name in ascending order.
Using `take()` as an Alternative
The `take()` method is an alias for `limit()` and works the same way:$users = User::take(5)->get();
Pagination Instead of Limit
If you want to paginate results instead of limiting them, you can use the `paginate()` method:$users = User::paginate(10); // 10 records per pageThis is useful for displaying results across multiple pages. Example in a Controller Here’s how you might use `limit()` in a Laravel controller:
```php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function index() { // Fetch the latest 5 users $users = User::orderBy('created_at', 'desc') ->limit(5) ->get(); return view('users.index', compact('users')); } }Points -> Use `limit()` to restrict the number of rows returned by a query. -> Combine `limit()` with `orderBy()` to control the order of results. -> Use `take()` as an alternative to `limit()`. -> For pagination, use `paginate()` instead of `limit()`. This is how you can use the `limit()` method in Laravel Eloquent to control the number of results returned by your queries.