Stop Repeating Yourself! Use Custom Stubs in Laravelš
Ever felt like a robot while coding? Every time you run php artisan make:controller, you get a blank file. Then, you manually add the same Traits, the same Helper classes, or the same try-catch blocks that you use in every single project.
Itās like buying a new phone and having to install the same 50 apps manually every single time. Wouldn't it be better if your phone came pre-installed with your favorite apps?
That is exactly what Custom Stubs do for your Laravel code!
What are Stubs? š¤
In simple words, Stubs are the "Blueprints" or "Templates" Laravel uses to create new files. When you ask Laravel to make a controller, it looks at its internal template and gives you a copy.
By default, these templates are hidden, but you can bring them out and change them!
How to Set It Up (The 2-Minute Guide)
1. Bring the Blueprints Out
Run this command in your terminal to copy Laravel's default templates into your project:
Bash
php artisan stub:publish
Now, check your project folder. You will see a new directory called /stubs. Inside, youāll find files like controller.plain.stub, model.stub, etc.
2. Add Your "Secret Sauce"
Open /stubs/controller.plain.stub. Letās say you want every controller to automatically use a specific ResponseTrait. Just edit the file like this:
PHP
<?php
namespace {{ namespace }};
use {{ rootNamespace }}Http\Controllers\Controller;
use App\Traits\ResponseTrait; // Adding your custom trait here!
class {{ class }} extends Controller
{
use ResponseTrait;
// Your default methods can go here too!
}
3. Enjoy the Magic āØ
The next time you run php artisan make:controller MyNewController, Laravel will use your version. Your trait and your custom structure will be there waiting for you. No more manual typing!
Why You Should Use This:
- Be Smart, Not Busy: Why spend 5 minutes on boilerplate when you can do it in 5 seconds?
- Team Consistency: If you are working in a team, everyone will follow the same file structure.
- Zero Typos: Since the code is pre-written in the stub, you won't make silly copy-paste mistakes.
Final Thoughts
Laravel is built to make developers happy. Customizing stubs is a small step that makes your daily coding life much smoother. Give it a try today!
What's next? Tomorrow, Iāll share how I handle API Responses globally so I never have to write return response()->json(...) ever again. Stay tuned!Ever felt like you're stuck in a loop, repeating the same lines of code over and over again? Every time you generate a new file in your Laravel project ā be it a Controller, a Model, a Request, or even a Custom Command ā you probably find yourself adding the same boilerplate code. Think about it:
- Adding specific
usestatements. - Implementing certain interfaces or extending custom base classes.
- Including traits for common functionalities like response handling or logging.
This isn't just time-consuming; it's mentally draining and prone to errors. It's like buying a brand new car and having to manually install the stereo, power windows, and air conditioning every time you get a new one! Wouldn't it be great if your new car came pre-loaded with all your favorite features and settings?
This is exactly where Custom Stubs in Laravel come to your rescue! They allow you to customize the default templates that Laravel uses to generate new files, making your development process faster, cleaner, and much more consistent.
What Exactly Are Stubs? š¤
At its core, a stub is simply a blueprint or a template. When you run an artisan make: command (e.g., make:controller, make:model), Laravel doesn't just pull a file out of thin air. It looks at its internal "stub" file ā a plain text file with a .stub extension ā and uses that as the base to generate your new class.
Think of it as a cookie cutter. Laravel has default cookie cutters for controllers, models, etc. But with custom stubs, you get to design your own cookie cutters!
Why Should You Even Bother with Custom Stubs?
If you're still on the fence, here are some compelling reasons why every Laravel developer should embrace custom stubs:
- Massive Time Savings: This is the most obvious benefit. If you save even 30 seconds on each generated file and you create dozens of files in a project, those seconds add up to hours. Imagine not having to type
use App\Traits\ApiResponseTrait;in every controller! - Code Consistency: Working in a team? Custom stubs ensure that every developer generates files that adhere to a consistent structure, naming conventions, and common traits. No more arguments about where to put that
responsemethod! - Reduced Errors (Typos Be Gone!): Manual copy-pasting or typing leads to typos. When your boilerplate is baked directly into the stub, the chances of introducing simple errors are drastically reduced.
- Enforce Best Practices: You can embed your project's specific best practices directly into the stubs. For instance, if every model needs a
protected $guarded = [];, you can put it directly in yourmodel.stub. - Become a Lazier, Smarter Developer: The goal isn't to work harder; it's to work smarter. Automating repetitive tasks is the hallmark of an efficient developer.
Getting Started: Unleash the Stubs!
Laravel, being the awesome framework it is, provides a simple way to bring these hidden blueprints into your project so you can modify them.
Step 1: "Publish" the Default Stubs
Open your terminal in your Laravel project's root directory and run this command:
Bash
php artisan stub:publish
What happened? Laravel just created a new directory in your project root called /stubs. Inside this folder, you'll find various .stub files like controller.plain.stub, model.stub, request.stub, etc. These are the exact templates Laravel uses by default.
Now, they are yours to modify!
Step 2: Customizing Your First Stub (Controller Example)
Let's take a common scenario. Many developers like to include a ResponseTrait in their controllers to handle consistent API responses.
- Now, open the
controller.plain.stubfile located in your newly created/stubsdirectory.
Edit it to include the use statement for your trait and then apply the trait within the class:PHP
<?php
namespace {{ namespace }};
use {{ rootNamespace }}Http\Controllers\Controller;
use App\Traits\ApiResponseTrait; // <--- Add this line for your trait
class {{ class }} extends Controller
{
use ApiResponseTrait; // <--- Add this line to use the trait
/**
* Handle the incoming request.
*/
public function __invoke(Request $request): Response
{
// You can even add default method structures here!
}
}
First, make sure you have your trait defined, for example:PHP
// app/Traits/ApiResponseTrait.php
<?php
namespace App\Traits;
use Illuminate\Http\JsonResponse;
trait ApiResponseTrait
{
protected function sendSuccessResponse($data = [], $message = 'Success', $statusCode = 200): JsonResponse
{
return response()->json([
'status' => true,
'message' => $message,
'data' => $data,
], $statusCode);
}
protected function sendErrorResponse($message = 'Error', $statusCode = 400, $errors = []): JsonResponse
{
return response()->json([
'status' => false,
'message' => $message,
'errors' => $errors,
], $statusCode);
}
}
Step 3: Test Your Custom Stub (The "Aha!" Moment)
Now, go back to your terminal and create a new controller:
Bash
php artisan make:controller MyAwesomeController
Open app/Http/Controllers/MyAwesomeController.php. You will see that Laravel has used your modified stub! The use App\Traits\ApiResponseTrait; statement and use ApiResponseTrait; are already there. Voila!
Beyond Controllers: More Stub Customization Ideas
The possibilities are endless! Think about:
- Models: Automatically add
protected $guarded = [];orprotected $fillable = [];, abootmethod for event observers, or common relationships. - Requests: Pre-add
authorize()to returntrueor add basic validation rules (return [];). - Commands: Set up the basic signature and description for your custom Artisan commands.
- Tests: Include common setup methods or assertion boilerplate.
Pro Tip: Creating Custom Stubs for Your Own Commands
You're not limited to modifying existing stubs. If you create your own custom make commands (e.g., php artisan make:repository), you can point them to your custom stub files! This gives you complete control over any file generation in your project.
Final Thoughts: Work Smarter, Not Harder
In the fast-paced world of web development, every second saved and every error prevented contributes to a smoother project. Laravel Custom Stubs are a simple yet incredibly powerful tool to streamline your workflow, enforce consistency, and ultimately, make you a more efficient and 'lazier' (in a good way!) developer.
Stop being a code-repeating robot. Empower your Laravel project with custom stubs today and feel the difference!
What's next? Tomorrow, Iāll dive into "Laravel Observers" ā a powerful way to keep an eye on your models and react to their events (like created, updated, deleted) without cluttering your models or controllers. It's like having a silent assistant for your database changes! Stay tuned!