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

jmfs's avatar
Level 6

Stored Procedure-Based Models

Hey, our company uses MSSQL for a bunch of our main DB infrastructure and uses Stored Procedures to streamline many requests across systems. What is the best way to build a model that uses SPs instead of tables? I just fooled around and came up with this that basically would overwrite the methods for functions like ::all() and ::find(), probably not the best solution. (using MySQL here, I know to use Exec and not CALL)

class Location extends Model {

    protected $table = null;

    public static function all($columns = array('*')) {
        // make all fillable
        Model::unguard();
        // start with empy array
        $locations = [];
        // get all locations from SP
        foreach (\DB::select('CALL getLocationAll();') as $attrs) {
            $locations[] = new Location((array)$attrs);
        }
        return new Collection($locations);
    }

    public static function find($id, $columns = array('*')) {
        // make all fillable
        Model::unguard();
        // get data
        $attrs = \DB::select('CALL getLocation(?);',[$id]);
        // return single store
        return new Location((array)$attrs[0]);
    }

    public function menu() {
        return Menu::find($this->id);
    }

}

Obviously, we'd need to add pagination to the SPs and when I try and make another custom method that would mirror a relationship (Location::find(1)->menu), it gives me an error:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

So is there a way to make a relationship just a simple method that calls another sp?

Anyone have suggestions or dealt with this before? Thank you.

0 likes
4 replies
itpushstudio's avatar

I was trying to do the same. I think that this is a good idea. Will be disconnected from artisan, but will work with MSSQL. Did you find anything else?

thepsion5's avatar

It seems like trying to fake it that way would have a hundred different esoteric edge-cases that would break as a result. What's the advantage in trying to make it behave like a typical eloquent model? Why not just use a plain PHP class with getters and setters?

itpushstudio's avatar

You mean without extending Model from that class? Do we need to save the file in the same directory, right?

tovisbratsburg's avatar

Is there a way to work with Stored Procedure-Based Models with Laravel 8?

Please or to participate in this conversation.