As developers, weāre always on the lookout for tools and techniques that make our work more efficient, customizable, and user-friendly. If youāre working with Laravel, youāre in luck! Today, Iāll show you how to combine Laravel stubs with the Laravel Prompts package to create a fully customizable and interactive code generation workflow.
By the end of this guide, youāll be able to generate code templates dynamically based on user input, all while maintaining the power and flexibility of Laravelās built-in tools. Ready to supercharge your development process? Letās dive in! šŖ
What Are Laravel Stubs?
Laravel stubs are template files used to generate boilerplate code in Laravel projects. Think of them as skeleton code that Laravel uses for commands like php artisan make:controller
or php artisan make:model
. You can customize these stubs to fit your project's needs, ensuring that your generated code matches your architecture and coding standards.
For example, by modifying the default controller.stub
, you can automatically include traits, middleware, or other boilerplate code every time you generate a new controller.
How to Use and Customize Laravel Stubs
- Locate and Publish Stubs:
Laravel keeps its default stubs hidden in the vendor
directory. Youāll need to publish them into your project if you want to customize them:
php artisan stub:publish
This will generate a stubs
directory in the root of your project where you can modify the available stubs, like controller.stub
or model.stub
.
2. Customize the Stub:
For example, letās add a custom trait to the controller stub:
// controller.stub example
namespace {{ namespace }};
use App\Traits\YourCustomTrait;
use Illuminate\Http\Request;
class {{ class }} extends Controller
{
use YourCustomTrait;
// Custom methods
}
Now, every time you generate a new controller, it will include the YourCustomTrait
by default.
To see more about stubs see part 1:
Unlock the Magic of Laravel Stubs: Supercharge Your Code Generation š
Hello, Laravel enthusiasts! šļø Welcome to the magical world of Laravel stubs ā a powerful tool that can save youā¦
What Is Laravel Prompts?
Laravel Prompts is an excellent package that adds interactive CLI prompts to your Laravel commands. Whether you need to gather user input or make your commands more dynamic, Laravel Prompts makes it easy.
Hereās how you can add interactive prompts to your Laravel commands using the package.
Installing Laravel Prompts
The latest versions of Laravel already include the Prompts package, so no need to install it separately. However, if youāre using a standalone PHP project, you can install it via Composer:
composer require laravel/prompts
More in https://laravel.com/docs/11.x/prompts
Combining Laravel Stubs and Prompts for Ultimate Flexibility
Letās combine Laravel stubs with Laravel Prompts to create an Artisan command that dynamically generates a controller based on user input!
Step 1: Create a Custom Artisan Command
First, weāll generate a new Artisan command using Laravelās make:command
command:
php artisan make:command GenerateCustomController
This will create a new command file in app/Console/Commands/GenerateCustomController.php
. Now, let's edit this command to use Laravel Prompts and interact with our stubs.
Step 2: Add Interactive Prompts to the Command
In our command, weāll use the Laravel Prompts package to gather user input. For example, weāll ask the user for the name of the controller, whether it should be a resource controller, and if it should include any specific traits.
Hereās the updated command:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use function Laravel\Prompts\text;
use function Laravel\Prompts\confirm;
class GenerateCustomController extends Command
{
/**
* The name and signature of the console command.
*/
protected $signature = 'make:custom-controller';
/**
* The console command description.
*/
protected $description = 'Generate a custom controller with interactive prompts';
public function handle()
{
// Prompt the user for the controller name
$controllerName = text('Enter the name of the controller:');
// Ask if the controller should be a resource controller
$isResource = confirm(
label: 'Should this be a resource controller?',
default: true,
yes: 'Yes, make it a resource controller',
no: 'No, keep it simple'
);
// Confirm if a custom trait should be included
$includeTrait = confirm(
label: 'Do you want to include a custom trait?',
default: false,
hint: 'You can always add traits later if needed.'
);
// Create the file using the stub template
$this->createController($controllerName, $isResource, $includeTrait);
}
private function createController($name, $isResource, $includeTrait)
{
// Define the stub file to use
$stubPath = base_path('stubs/controller.stub');
$stub = file_get_contents($stubPath);
// Replace placeholders in the stub
$stub = str_replace('{{ class }}', $name, $stub);
if ($isResource) {
// Modify stub to include resource methods
$stub = str_replace('// Methods', 'public function index() {}', $stub);
}
if ($includeTrait) {
// Add trait usage
$stub = str_replace('// Traits', 'use App\\Traits\\YourCustomTrait;', $stub);
} else {
$stub = str_replace('// Traits', '', $stub);
}
// Save the generated file
$filePath = app_path("Http/Controllers/{$name}.php");
file_put_contents($filePath, $stub);
$this->info("Controller {$name} created successfully!");
}
}
Explanation:
Prompts: We ask the user for input using
text
for the controller name andconfirm
for yes/no questions. These prompts make the command more interactive and allow the user to customize the generated controller.Custom Stub: We load the controller stub file, replace placeholders (
{{ class }}
), and adjust the content based on user input (whether to include a trait or resource methods).Generating the File: The final controller is saved to the
app/Http/Controllers
directory.
See more of commands at https://laravel.com/docs/11.x/artisan#command-structure
Step 3: Customize the Stub for Dynamic Options
Now, letās update the controller.stub
file to accommodate the changes based on the userās input.
Hereās an example of the updated controller.stub
:
<?php
namespace {{ namespace }};
use Illuminate\Http\Request;
// Traits
class {{ class }} extends Controller
{
// Traits
// Methods
}
The placeholders like {{ class }}
and // Traits
will be replaced dynamically by the Artisan command based on the userās selections.
Step 4: Testing the Command
With everything in place, run the command and watch the magic happen:
php artisan make:custom-controller
Youāll be prompted for the controller name, whether it should be a resource controller, and if it should include a custom trait. Based on your input, Laravel will generate a fully customized controller for you!
Advanced Customization
Once youāve mastered the basics, feel free to add more prompts to capture even more details for your stubs. For example, you could:
Create more complex stubs for models, service classes, migrations, etc.
Use validation on your prompts to ensure the user enters valid data.
Use a more advanced file structure ( A class for stubs, interfaces, etc )
Laravel Prompts and stubs give you an incredible amount of flexibility. With this setup, you can automate code generation to fit your exact needs ā saving time and boosting productivity. š
Conclusion
By combining Laravel stubs with the Laravel Prompts package, you can create powerful, interactive command-line tools that streamline your development process. This approach not only saves time but also ensures consistency and customization across your entire codebase.
Ready to take your Laravel development to the next level? Try integrating Laravel Prompts and stubs in your next project and see the productivity boost for yourself!
Happy automating! šāļø
Feel free to share your thoughts, ideas, and projects using this approach in the comments! Letās grow together as Laravel developers.
Top comments (0)