I have Model called Post. In my DB I have fields like "views" and "likes".
I need to add custom field to my SELECT request like "reactions" that do "views + likes".
Using Attributes is bad idea because I need to use "reactions" in WHERE with pagination.
Here the code I need to work
$posts = Post::where('reactions', '>', 100)->paginate();
How can I make auto added field "reactions" all my requests?
2
Answers
You cannot use alias in WHERE clause.
Copied from MySQL documentation and this question
As pointed in the document, using HAVING instead may do the work. Make sure to give a read at this question too: WHERE vs HAVING.
You may use in Laravel query builder like bellow:
to do this you need to make a static function in your model (or put it in a helper function)
In your Post Model.php
and use it anywhere