DEV Community

Cover image for Unlock the code generation of Laravel (part 2): Stubs with Laravel Promts šŸ’»šŸš€
AdriƔnColom
AdriƔnColom

Posted on • Originally published at Medium

Unlock the code generation of Laravel (part 2): Stubs with Laravel Promts šŸ’»šŸš€

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

  1. 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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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ā€¦

medium.com

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Prompts: We ask the user for input using text for the 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, replace placeholders ({{ class }}), and adjust the content based on user input (whether to include a trait or resource methods).

  3. 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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)