Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FareedR's avatar

How can I query using Accessor that I defined in Model

Model.php
public function getStatusAttribute()
{
    if($this->profit == 0 && $this->loss == 0){
            return 'Not Traded';
        }elseif($this->loss > $this->profit ) {
            return 'Loss';
        }elseif($this->profit == $this->loss){
            return 'Neutral';
        }else{
            return 'Profit';
        }
}
Controller.php
public function get_model_status()
{
     // how can i query based on accessor that i defined in Model .
}
0 likes
10 replies
Sinnbeck's avatar

You cannot query based on an accessor. It is only for transforming what comes out of the database.

You should instead make a scope. What do you plan to query on? Non traded?

public function scopeTraded($query) 
{
    $query->where('loss', 0)->where('profit', 0);
}
Sinnbeck's avatar

Or if you just need to check the status for a record (don't call the method directly)

$status = Model::find(1)->status;
FareedR's avatar

i want to query all data that has status " Profit " . i get an error for this method . Column not found: 1054 Unknown column 'status' . Note that , i didnt have any attribute for "status" . Stock "status" based on getStatusAttribute() method .

Stock.php
public function scopeProfit($query)
    {
        return $query->where('status','Profit');
    }

Controller.php
  $top_profit  = Stock::profit()->get();

Sinnbeck's avatar

Your scope cannot use accessors either.

Your scope needs to make a query that defines all those checks in the accessor

Sinnbeck's avatar

Something like

public function scopeProfit($query) 
{
    $query->where('loss', '>', 0)->where('profit', '>', 0)->whereColumn('profit', '>', 'loss'); 
}
FareedR's avatar

based on my understanding and your suggestion method . i need to add a new column for profit and loss . am i right ? define the status based on that . am i right ?

FareedR's avatar

also accessors .. i think i need to add new column for that .

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Yes,might be a good idea. The point is that you need to make real queries to the database with real table names. Scopes are just to make them reusable

And accessors are only for presentation, not queries

FareedR's avatar

thank you for your time . i solved it by added new column .

Please or to participate in this conversation.