?
What do you expect as result?
A scope is filter , ...
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a raw query that I would like to use as a scope function so that I may simply call the function to get all the data I need instead of writing out all the inner joins using the model.
something like this:
public function scopeGetMyData(){
return $query->raw(" SELECT * FROM table LEFT JOIN table2 on table2.id = table.id");
}
I know I could do something like return DB::select(DB::raw($sqlQuery));, but if I'm doing that is there any point in putting this in the model? Why not just put it somewhere else like a controller or another class.
This is ugly anyway, but you can do it using eloquent, it does not have to be raw even though you can use the selectRaw method.
public function scopeGetMyData( Builder $query )
{
return $query->leftJoin('table2', 'table2.id', '=', 'table.table2_id');
}
so then:
Table::select(.... columns here ...)->where('table.id', 1)->getMyData()->first();
use selectRaw if you want to add aliases as well.
Please or to participate in this conversation.