Laravel Stubs is a package that allows you to customize the default stub files used by Laravel when generating various components, such as controllers, models, migrations, and more. By customizing these stubs, you can tailor the generated code to fit your application’s specific needs and standards.
Installation
To install the package, you can use Composer:
1 |
composer require --dev laravel/stubs |
Customizing Stubs
Once installed, you can publish the default stubs to your application using the following Artisan command:
1 |
php artisan stubs:publish |
This command will create a stubs
directory in your application’s root folder, containing all the default stubs used by Laravel.
Modifying Stubs
- Locate Stubs: After running the publish command, you will find the stubs in the
stubs
directory. The stubs correspond to various Laravel components, such as:controller.stub
model.stub
migration.stub
factory.stub
- etc.
- Edit Stubs: You can modify these stub files to change the default structure or add custom code that should be included whenever you generate a new component. For example, you might want to add import statements or custom methods to your controller stub.
Example: Customizing a Controller Stub:
php
12345678910111213namespace {{ namespace }};use Illuminate\Http\Request;use App\Http\Controllers\Controller;class {{ class }} extends Controller{// Custom methodpublic function customMethod(){// Your custom code here}}
Generating Components
After customizing your stubs, you can generate components as usual using Artisan commands, and they will use your modified stubs. For example:
- To create a new controller:
1php artisan make:controller MyController - To create a new model:
1php artisan make:model MyModel
Example Output
When you generate a new controller after customizing the stub, the output might look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class MyController extends Controller { // Custom method public function customMethod() { // Your custom code here } public function index() { // Default index method } } |
Benefits of Customizing Stubs
- Consistency: Ensures that all generated files adhere to your coding standards and practices.
- Reduced Boilerplate: Reduces repetitive code and increases productivity by generating files with your common patterns.
- Easy Maintenance: Easier to maintain and update your code base if all components are generated with a consistent structure.
Conclusion
The Laravel Stubs package offers a straightforward way to customize the default code generation behavior in your Laravel applications. By editing the stub files, you can ensure that all components are generated according to your specifications, improving code quality and consistency across your application