Lets say I have a function that returns a builder. In case this builder cannot be returned, I want to return an empty builder - meaning, a builder which doesn't point to any data. One which if you do a get(), you will get empty collection. Any idea?
Asked
Active
Viewed 5,917 times
20
-
I think you mean a builder without any restrictions, i.e. if you do a get you will get every row. This would fit to your selected answer. – Adam Mar 22 '19 at 15:56
2 Answers
28
This is how you do it:
$builder = Post::query();

Antonio Carlos Ribeiro
- 86,191
- 22
- 213
- 204
-
7This is different from what the OP asked: If you call get() on this query it will return all values in the database instead of nothing as OP required. However, this was useful for me since I wanted exactly this behavior. – VinGarcia Apr 23 '18 at 18:57
-
@VinGarcia I think the OP was just asking for the wrong thing. This is an empty builder. – Adam Mar 22 '19 at 15:57
6
If your model has primary key, you can do this as a workaround:
$builder = Post::query()->whereNull('id')

Lam Kwok Shing
- 61
- 1
- 3
-
2
-
is there any other way to do this without searching the database. – Waseem Almoliky Apr 12 '22 at 12:32