How to retrieve records that meet specific criteria (e.g., where clauses) using Eloquent in Laravel?

To retrieve records that meet specific criteria using Eloquent in Laravel, follow these steps:

  1. Create a new Eloquent model for the table you want to query. For example, if you want to query the users table, create a User model:
php artisan make:model User
  1. In your controller or wherever you want to retrieve the records, import the model:
use App\Models\User;
  1. Use the where method on the model to add the criteria. For example, if you want to retrieve users with a certain status column value:
$users = User::where('status', 'active')->get();

This retrieves all users where status is equal to "active".

  1. You can chain multiple where methods to add more criteria. For example, if you want to retrieve users with a certain status and role:
$users = User::where('status', 'active') ->where('role', 'admin') ->get();
  1. You can also use other comparison operators such as >, <, >=, <=, <>, etc. For example, if you want to retrieve users with an age greater than 18:
$users = User::where('age', '>', 18)->get();
  1. To retrieve a single record based on the criteria, you can use the first method instead of get:
$user = User::where('email', '[email protected]')->first();

This retrieves the first user with an email of "[email protected]".

These are the basic steps to retrieve records that meet specific criteria using Eloquent in Laravel. You can further enhance the query by using joins, sorting, pagination, or applying additional constraints as needed.