nowox
nowox

Reputation: 29106

How to select a RAW column in an Eloquent Model?

I would like to add a custom column in my Eloquent model such as:

class Shape extends Eloquent
{
    public function getAreaAttribute()
    {
        return $this->width * $this->height;
    }
}

Which allows to build a query such as this:

Shape::where('area', '>', 42)->get();

What I could do is:

Shape::select(['*', DB::RAW('width * height AS area')])->where('area', '>', 42)->get();

But this is not in my model. Is it possible to get something like:

class Shape extends Eloquent
{
    public function getAreaColumn()
    {
        return DB::RAW('width * height AS area')
    }
}

Upvotes: 2

Views: 3940

Answers (2)

Free Code
Free Code

Reputation: 283

I hope this code will help you

$result = DB::table('shape')
                 ->select(DB::raw('width * height AS area'))
                 ->where('area', '>', 42)
                 ->get();

Upvotes: -2

Taha Paksu
Taha Paksu

Reputation: 15616

You can define this in your migration:

$table->integer('area')->virtualAs('height * width');

to be generated on every read, or

$table->integer('area')->storedAs('height * width');

if you want to store the column in the database if you don't want the generation to be always.

and then add the area column to your model. This way you can use the field in both queries and models.

Upvotes: 3

Related Questions