Unlock the code generation of Laravel (part 2): Stubs with Laravel Promts 💻🚀
December 24, 2024

Unlock the code generation of Laravel (part 2): Stubs with Laravel Promts 💻🚀

As developers, we’re always on the lookout for tools and technologies that make our work more efficient, customizable, and user-friendly. If you are working with Lavelleyou are in luck! Today I’m going to show you how Merge Laravel stubs and Laravel Tips package to create a fully customizable and interactive Code generation workflow.

By the end of this guide, you’ll be able to dynamically generate code templates based on user input while maintaining the power and flexibility of Laravel’s built-in tools. Ready to accelerate your development process? Let’s dive in! 💪

Laravel stub Is a template file used to generate boilerplate code in Laravel projects. Think of them as Laravel’s skeleton code for commands, such as php artisan make:controller or php artisan make:model. You can customize these stubs to fit your project needs, ensuring that the generated code adheres to your architecture and coding standards.

For example, by modifying the default controller.stubyou can automatically include features, middleware, or other boilerplate code every time you generate a new controller.

  1. Find and publish the stub:

Laravel hides its default stubs in vendor Table of contents. If you want to customize them, you need to publish them to your project:

php artisan stub:publish
Enter full screen mode

Exit full screen mode

This will generate a stubs Directory in the project root where you can modify the available stubs, e.g. controller.stub or model.stub.

2. Customized 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
}
Enter full screen mode

Exit full screen mode

Now, every time a new controller is spawned, it will contain YourCustomTrait By default.

To learn more about stubs, see Part 1:



Hello, Laravel lovers! 🖐️ Welcome to the amazing world of Laravel stubs – a powerful tool that can save you…

media website

Laravel Tips is an excellent package that adds interactive CLI prompts to your Laravel commands. Whether you need to collect user input or make a command more dynamic, Laravel Tips Make it easy.

Here’s how to use this kit to add interactive prompts to Laravel commands.

Latest versions of Laravel already include the Prompts package, so there is no need to install it separately. However, if you use a standalone PHP project, you can install it through Composer:

composer require laravel/prompts
Enter full screen mode

Exit full screen mode

For more information, see https://laravel.com/docs/11.x/prompts

let’s combine Laravel stub and Laravel Tips Create an Artisan command to dynamically generate controllers based on user input!



Step 1: Create custom Artisan commands

First, we will generate a new Artisan directive using Laravel make:command Order:

php artisan make:command GenerateCustomController
Enter full screen mode

Exit full screen mode

This will create a new command file app/Console/Commands/GenerateCustomController.php. Now, let’s edit this command to use Laravel prompts and interact with our stub.



Step 2: Add interactive prompts for commands

In our command we will use Laravel Tips package to collect user input. For example, we’ll ask the consumer controller for its name, whether it should be a resource controller, and whether it should contain any specific characteristics.

Here is the updated command:



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!");
    }
}
Enter full screen mode

Exit full screen mode

explain:

  1. hint: We ask the user to enter text For controller name and confirm For yes/no questions. These prompts make the command more interactive and allow the user to customize the generated controller.

  2. Custom stub: We load the controller stub file, replacing the placeholders ({{ class }}) and adjust the content based on user input (whether it contains traits or resource methods).

  3. Generate file: The final controller is stored in app/Http/Controllers Table of contents.

View more instructions https://laravel.com/docs/11.x/artisan#command-struct



Step 3: Customize the stub for dynamic options

Now, let’s update controller.stub Document to accommodate changes based on user input.

This is the updated example controller.stub:



namespace {{ namespace }};

use Illuminate\Http\Request;
// Traits

class {{ class }} extends Controller
{
    // Traits

    // Methods
}
Enter full screen mode

Exit full screen mode

placeholder is like {{ class }} and // Traits It will be dynamically replaced by Artisan commands according to the user’s selection.



Step 4: Test the command

Once everything is ready, run the command and watch the magic happen:

php artisan make:custom-controller
Enter full screen mode

Exit full screen mode

You will be prompted for a controller name, whether it should be a resource controller, and whether it should contain custom characteristics. Based on your input, Laravel will generate a fully customized controller for you!

Once you’ve mastered the basics, feel free to add more prompts to capture more details of the stub. For example, you can:

  • Create more complex stubs for models, service classes, migrations, and more.

  • Validate the prompt to ensure the user enters valid data.

  • Use higher-order file structures (categories of stubs, interfaces, etc.)

Laravel prompts and stubs give you incredible flexibility. With this setup, you can automatically generate code to meet your exact needs – saving time and increasing productivity. 🚀

through combination Laravel stub and Laravel Tips Within the suite, you can build powerful, interactive command-line tools to streamline your development process. This approach not only saves time, but also ensures consistency and customization throughout the code base.

Ready to take your Laravel development to the next level? Try integrating Laravel Prompts and Stubs into your next project and see the productivity boost for yourself!

Happy automation! 😄⚙️

Feel free to share your thoughts, ideas, and projects using this method in the comments! Let’s grow together as Laravel developers.

2024-12-24 14:43:56

Leave a Reply

Your email address will not be published. Required fields are marked *