Here is the query I tried to write and gives an error
$users =User::has('subscriptions', function (Builder $q) {
$q->whereNotNull('ends_at');
})->get();
Getting this error
SQLSTATE[42601]: Syntax error: 7 ERROR: SELECT * with no tables specified is not valid LINE 1: ...sers"."id" = "subscriptions"."user_id") = (select * where "e... ^ (SQL: select * from "users" where (select count(*) from "subscriptions" where "users"."id" = "subscriptions"."user_id") = (select * where "ends_at" > now) and "users"."deleted_at" is null)
When I write this code I get results but need to filter result to get a list of subscribed users without calling User::all()
then loop to filter.
User::has('subscriptions')->get();
4
Answers
Solution is here 😁
Have a good day
use
Read Constraining Eager Loads
Do it like this
$users = User::with(['subscriptions' => static function ($query) { $query->whereNotNull('ends_at'); }])->get();
Or,
This will give you only subscribed users. But if you fetch all the users and then apply filter to the fetched result, then every row will be fetched from the database, which is not a good practice.