Search code examples
phplaraveleloquent

Laravel custom query field in model


I have a Model called Post. In my DB I have fields like "views" and "likes". I need to add a custom field to my SELECT request like "reactions" that do "views + likes". Using Attributes is a bad idea because I need to use "reactions" in WHERE with pagination.

Here is the code I need to work

$posts = Post::where('reactions', '>', 100)->paginate();

How can I make auto added field "reactions" all my requests?


Solution

  • You cannot use alias in WHERE clause.

    Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.

    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:

    $posts = Post::select(['*', DB::raw('(views + likes) as reactions')])
        ->having('reactions', '>', 100)
        ->paginate();