Question

In my Eloquent collections, I'd like to add an extra column called "editable". "Editable" should be included in each query I run on some models. "Editable" show either be true or false, based on a raw query.

So I have a query that should be runned in each query on my models. Adding an extra column to my collection. The value of "editable" is determined by a raw query.

What is the best way to do this?

Was it helpful?

Solution

You could add an addSelect() method to your query chain to include the custom attribute..

Something like

$results = YourModelClass::select("*")
    ->addSelect(DB::raw("IF(condition,1,0) AS editable"))
    ->get();

In the above case, you would replace condition with your relevant SQL statement that would be evaluated per-row as part of the query. If the statement is true, then editable = 1 and if false then editable = 0 for each row returned to your Collection.

EDIT: I just saw that you want this on every query, so you probably would need a global scope/trait for your models, but the above technique for including the extra attribute should be the correct one.

I won't copy/paste the documentation on adding global scopes, that's in the core Laravel docs and I'm sure you can find it.

OTHER TIPS

You can add a custom getter to your model:

public function getEditableAttribute()
{
    /* return result from your raw query here */;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top