- X OR Y Sometimes we may want to query a database table using two different conditions, where only one of them needs to be true to retrieve the results. In such cases, we can use the “orWhere” method in Laravel Eloquent. For example:
$users = User::where('status', '=', 'active') ->orWhere('last_login_at', '>', Carbon::now()->subMonths(6)) ->get();
In the example above, we’re querying the “users” table for all users who are either currently active or who have logged in within the last six months.
- Find OR Fail The “find” method in Laravel Eloquent is commonly used to retrieve a record by its primary key. However, if the record does not exist, it will return null. In some cases, we may want to throw an exception instead. For this, we can use the “findOrFail” method. For example:
$user = User::findOrFail($id);
In the example above, we’re retrieving a user by their primary key. If the user does not exist, a “ModelNotFoundException” exception will be thrown.
- First OR Create Sometimes we may want to retrieve a record if it exists, or create a new record if it doesn’t. In such cases, we can use the “firstOrCreate” method in Laravel Eloquent. For example:
$user = User::where('email', '=', $email)->firstOrCreate([ 'name' => $name, 'password' => $password, ]);
In the example above, we’re querying the “users” table for a user with the specified email. If the user exists, we retrieve that user. If the user does not exist, we create a new user with the specified name and password.
By utilizing these Laravel Eloquent tips, we can improve our queries and make our code more efficient and readable.