DEV Community

Cover image for Unlock the Magic of Laravel Stubs: Supercharge Your Code Generation 🚀
AdriánColom
AdriánColom

Posted on • Originally published at Medium

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 countless hours of repetitive coding. If you’ve ever wished for a coding assistant to handle the mundane tasks, your wish is about to come true. In this post, we’ll explore what Laravel stubs are, how to use them, and how they can be customized to fit your needs.

What Are Laravel Stubs? 🛠️

Think of Laravel stubs as the blueprint for your code. Imagine building a house: you wouldn’t start from scratch each time. Instead, you’d use a blueprint — adjusting it for each project but always starting from a solid foundation. Laravel stubs work the same way. They’re pre-designed templates that let you generate code quickly and consistently, just like laying a foundation for a new building.

Laravel uses these stubs to create boilerplate code when you run commands like php artisan make:controller, php artisan make:model, and others. By customizing these stubs, you can ensure that your generated code fits perfectly with your project’s specific needs, just as an architect customizes blueprints to fit the unique requirements of a building.

Why Should You Care About Stubs? 🧐

  • Consistency: Keep your codebase consistently clean and uniform across every file.

  • Efficiency: Accelerate your workflow by instantly generating repetitive code.

  • Customization: Fine-tune your stubs to precisely match your project’s unique needs.

Getting Started with Laravel Stubs

Step 1: Locate the Default Stubs 🗂️

Laravel’s default stubs are stored in the vendor/laravel/framework/src/Illuminate/Foundation/Console/stubs directory. Think of this directory as the storage room for all your construction blueprints. Take a moment to browse through it—you’ll find templates for controllers, models, migrations, and more.

Step 2: Publish the Stubs 🛠️

To start customizing stubs, you need to bring them into your project’s root directory. Run the following Artisan command:

php artisan stub:publish
Enter fullscreen mode Exit fullscreen mode

This will create a stubs directory in the root of your Laravel application. It’s like setting up your own blueprint station on-site, ready for customization.

Step 3: Customize Your Stubs 🎨

Now, the real fun begins — customizing the stubs to suit your needs. Open the stubs directory and edit the files as you see fit. For example, if you want all your controllers to include a specific trait by default, you can modify the controller.stub:

// controller.stub example
namespace {{ namespace }};

use App\Traits\YourMagicTrait;
use Illuminate\Http\Request;
class {{ class }} extends Controller
{
    use YourMagicTrait;

    // Your custom methods
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Generate Code Using Customized Stubs ⚡

Once your custom stubs are in place, generating code becomes a breeze. Use Artisan commands as usual, and Laravel will use your custom stubs:

php artisan make:controller MagicController
Enter fullscreen mode Exit fullscreen mode

It’s like having a construction crew that knows exactly where every beam and wall goes, saving you time and ensuring consistency.

Practical Examples 🎯

Example 1: Custom Controller Stub

Let’s say you always use a specific trait in your controllers. Modify controller.stub like this:

use App\Traits\YourMagicTrait;

class {{ class }} extends Controller
{
    use YourMagicTrait;

    // Additional methods
}
Enter fullscreen mode Exit fullscreen mode

Example 2: Custom Migration Stub

If you want every new database table to include default columns, such as a column whose name is active, edit the migration.stub:

public function up()
{
    Schema::create('{{ table }}', function (Blueprint $table) {
        $table->id();
        $table->timestamps();
        $table->boolean('active')->default();
        // Your default columns
    });
}
Enter fullscreen mode Exit fullscreen mode

Example 3: Advanced Controller Customization

Suppose you frequently add specific logic or dependencies to your controllers — like integrating a custom HVAC system into every new building. Customize your controller.stub to include these by default:

// controller.stub example
namespace {{ namespace }};

use App\Services\YourCustomService;
use Illuminate\Http\Request;

class {{ class }} extends Controller
{
    public function __construct(
      protected YourCustomService $service
    ) {}

    // Your custom methods
}
Enter fullscreen mode Exit fullscreen mode

Advanced Customization Tips 🧠

1. Using Placeholder Variables

Laravel stubs use placeholder variables like {{ namespace }}, {{ class }}, and more, which are dynamically replaced when files are generated. You can even add custom placeholders, just like marking specific spots on your blueprint for unique features:

// custom.stub
namespace {{ namespace }};

class {{ class }}
{
    public function customMethod()
    {
        // {{ customPlaceholder }}
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Creating Custom Artisan Commands

If you want to take automation to the next level, creating custom Artisan commands can make your workflow even smoother. Laravel makes it easy to create your commands, which can leverage your custom stubs:

  1. Create a New Command: Use the Artisan command to generate a new custom command:
php artisan make:command CustomMakeCommand
Enter fullscreen mode Exit fullscreen mode

This command generates a new file in app/Console/Commands/CustomMakeCommand.php.

2. Define the Command Logic: Open the generated file and define the logic of your command. Here’s how you might use a custom stub within your new command:

// CustomMakeCommand.php
namespace App\Console\Commands;

use Illuminate\Console\Command;

class CustomMakeCommand extends Command
{
    protected $signature = 'make:custom {name}';
    protected $description = 'Create a custom class with a custom stub';

    public function handle()
    {
        $name = $this->argument('name');
        $stub = file_get_contents(base_path('stubs/custom.stub'));
        $content = str_replace('{{ class }}', $name, $stub);
        file_put_contents(app_path("{$name}.php"), $content);
        $this->info("Custom class {$name} created successfully!");
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Run Your Custom Command: You can now use this custom command just like any other Artisan command:

php artisan make:custom MyCustomClass
Enter fullscreen mode Exit fullscreen mode

This command will generate a new class file using your custom stub template, saving you time and ensuring consistency.

Conclusion 🎉

Laravel stubs are a powerful feature that can save you time and ensure consistency across your projects. By customizing these templates, you can streamline your workflow and maintain high coding standards effortlessly. And with a bit of creativity, you could even turn your mastery of Laravel stubs into a profitable venture.

So, go ahead — unlock the magic of Laravel stubs, and let them work their wonders for you. Remember, with great power comes great responsibility.

Happy coding, and may the stubs be ever in your favor! 🚀

Top comments (0)