phplaravellaravel-5.4

Laravel - Unable to override the create method for a model


When overriding the base Laravel model create method, the application fails. No errors are sent back to the browser, and the server logs are empty. The strange thing, it works just fine without the override. Not sure what I'm doing wrong.

Simplified controller function:

public function save(Request $request, $id = 0) {
    $myModel = MyModel::find($id);
    $data = $request->all();

    if (!$myModel) // Create a new row
    {
        $myModel = MyModel::create($data);
    }

    // ...
}

This works fine until I add this function to the model:

class MyModel extends Model
{
    // ...

    public static function create($attributes = [])
    {
        return parent::create($attributes);
    }

    // ...
}

Just to clarify, I'm not looking for a different way to implement this. I just need to know why the parent call is failing for me.

Here's some server info...


Solution

  • The explanation is that the public static function create() is not defined in the Illuminate\Database\Eloquent\Model class.

    Is handled as dynamic method call, that is is handled by calling the function:

    public static function __callStatic($method, $parameters)
    

    In the Illuminate\Database\Eloquent\Model class.

    At the end the create() function is defined in the Illuminate\Database\Query\Builder class. That is the reason you cant override it in your Model and call parent::create()

    IMHO I have not tested entirely, you could try with:

    public static function create($attributes)
    {
        return (new static)->newQuery()->create($attributes);
    }