To retrieve records that meet specific criteria using Eloquent in Laravel, follow these steps:
users
table, create a User
model:php artisan make:model User
use App\Models\User;
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".
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();
>
, <
, >=
, <=
, <>
, etc. For example, if you want to retrieve users with an age
greater than 18:$users = User::where('age', '>', 18)->get();
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.