skip to Main Content

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


  1. 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();
    
    Login or Signup to reply.
  2. 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

    public static function withReactions()
    {
        return static::select(['*', DB::raw('(views + likes) as reactions')]);
    }
    

    and use it anywhere

    $posts = Post::withReactions()->having("reactions",'>',100)->paginate();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search