Static Method Within Model to Save and Return Instance of Itself

Posted 1 year ago by Nicholaus

I'm doing something like this and have gotten some weird behavior:

The Eloquent model class: class MyModel extends Model {

public static function saveObjToModel($apiObj) {

    $myModel = MyModel::firstOrNew(['id' => $apiObj->id]);
    $myModel->name = $apiObj->name;
    return $myModel;


Calling script: $myModel = MyModel::saveObjToModel($apiObj); echo $myModel->id; // this returns '0'

$myModel = MyModel::find($apiObj->id); echo $myModel->id; // this returns actual ID of the persisted model

Am I breaking some kind of design pattern rule for Laravel/PHP? Is there some other way I should be doing this?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.