How to use Jenssegers\Mongodb\Eloquent\Model instead of Illuminate\Database\Eloquent\Model in php artisan make:model command

Viewed 736

I'm developing a webapp with Laravel and MongoDB (jenssegers/laravel-mongodb).

While creating a new model with php artisan make:model, the command uses Illuminate\Database\Eloquent\Model declaration in the file and every time I need to replace Illuminate\Database\Eloquent\Model with Jenssegers\Mongodb\Eloquent\Model manually.

Is there a way to automate the process?

2 Answers

It doesn't look like the package provides an Artisan command to create a MongoDB model stub, which seems like a bit of an oversight. However, it's not terribly hard to create this kind of generator command for Artisan yourself if you need it.

The model make command is at https://github.com/laravel/framework/blob/5.7/src/Illuminate/Foundation/Console/ModelMakeCommand.php and the stub file used to create it is at https://github.com/laravel/framework/blob/5.7/src/Illuminate/Foundation/Console/stubs/model.stub. If you extend the command class to replace the stub file with your MongoDB version, and amend the stub file to be a MongoDB model, then you should be able to create a command for generating MongoDB models. It might even be worth forking the package to add this and submitting a pull request to get it added to the package. I would refer to the part of the Laravel documentation that deals with Artisan for more details, as that describes the process of adding your own Artisan commands in detail.

Another approach would be to write your own class generator and then overwrite the command make:model

Add the following in the file routes/console.php to override the command

use Path\To\Class\MyCustomClassGenerator;

Artisan::command('make:model', function(){
  new MyCustomClassGenerator();
  $this->comment('new MongoDB Model generated');
});
Related