π Introducing Traitify β Simplifying Laravel Development with Reusable Traits and Contracts π
Nasrul Hazim Bin Mohamad
Posted on October 15, 2024
Hey, Laravel developers! π
Iβm excited to introduce Traitify, a newly released Laravel package designed to streamline your development workflow by providing reusable traits and contracts. Traitify empowers you to write cleaner, more maintainable code, allowing you to focus on what matters most β building amazing applications.
Whether you're dealing with UUIDs, tokens, user handling, search functionality, API responses, or complex relationships, Traitify has got you covered. And the best part? It's available now on GitHub! π
π Check it out: https://github.com/cleaniquecoders/traitify
π Key Features with Examples
Hereβs a breakdown of what Traitify brings to the table, along with practical examples.
1. UUID Management π
Automatically generate UUIDs for your models on creation. No more manual work β just add the InteractsWithUuid
trait and youβre good to go!
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithUuid;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithUuid;
protected $fillable = ['title', 'content'];
}
Every time a new Post
is created, a UUID will automatically be generated for the model.
$post = Post::create([
'title' => 'My first post',
'content' => 'Content goes here'
]);
echo $post->uuid; // Outputs a unique UUID
2. User Interaction π€
Easily assign the authenticated user to your models using the InteractsWithUser
trait. This is great for tracking who created or updated a model.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithUser;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithUser;
protected $fillable = ['title', 'content', 'user_id'];
}
On creation, the authenticated userβs ID is automatically assigned to the user_id
column.
$post = Post::create([
'title' => 'Another post',
'content' => 'More content'
]);
echo $post->user_id; // Outputs the ID of the currently authenticated user
3. Token Handling π
Secure your models by automatically generating random 128-character tokens. Use InteractsWithToken
to manage tokens seamlessly.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithToken;
use Illuminate\Database\Eloquent\Model;
class ApiToken extends Model
{
use InteractsWithToken;
protected $fillable = ['name', 'token'];
}
Tokens are automatically generated for new models.
$token = ApiToken::create(['name' => 'My API Token']);
echo $token->token; // Outputs a 128-character random token
4. Search Functionality π
Enhance your models with powerful, case-insensitive search capabilities using InteractsWithSearchable
. Perform searches across one or multiple fields with minimal setup.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithSearchable;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithSearchable;
protected $fillable = ['title', 'content'];
}
Search by any field in a case-insensitive manner:
$posts = Post::search('title', 'first')->get();
You can also search across multiple fields:
$posts = Post::search(['title', 'content'], 'keyword')->get();
5. Resource URL Generation π
Need to generate URLs for resources dynamically? The InteractsWithResourceRoute
trait simplifies this process, allowing you to create routes like index
or show
with ease.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithResourceRoute;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithResourceRoute;
}
Generate URLs dynamically:
$post = Post::find(1);
echo $post->getResourceUrl(); // Outputs the URL for the index route
echo $post->getResourceUrl('show'); // Outputs the URL for the show route
6. Meta Management π§©
Manage meta fields dynamically in your models using InteractsWithMeta
. You can define default meta values and cast the meta
attribute to an array automatically.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithMeta;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithMeta;
protected $fillable = ['title', 'content', 'meta'];
}
Automatically set meta fields when creating a model:
$post = Post::create([
'title' => 'Meta Post',
'content' => 'Meta content',
'meta' => [
'some' => 'random',
'data' => 'in here'
]
]);
7. Enum Handling ποΈ
Handle enums efficiently by providing enum values, labels, and descriptions with InteractsWithEnum
.
Example:
enum PostStatus: string
{
use CleaniqueCoders\Traitify\Concerns\InteractsWithEnum;
case DRAFT = 'draft';
case PUBLISHED = 'published';
public function label(): string
{
return match ($this) {
self::DRAFT => 'Draft',
self::PUBLISHED => 'Published',
};
}
public function description(): string
{
return match ($this) {
self::DRAFT => 'Post is in draft state',
self::PUBLISHED => 'Post is published',
};
}
}
Retrieve enum options for form inputs:
$options = PostStatus::options();
8. Eager Loading Details βοΈ
The InteractsWithDetails
trait allows you to define related details in your models and apply eager loading effortlessly.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithDetails;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithDetails;
protected $with_details = ['comments'];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Load related details automatically:
$post = Post::withDetails()->find(1);
9. Standardized API Responses π
Need to standardize your API responses? InteractsWithApi
helps you return consistent API data, messages, and status codes.
Example:
use CleaniqueCoders\Traitify\Concerns\InteractsWithApi;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use InteractsWithApi;
public function getMessage(): string
{
return 'Post retrieved successfully';
}
}
Retrieve the API response:
$post = Post::find(1);
$response = $post->getApiResponse(new Request());
π Contracts to Define Structure and Flexibility
Here are examples for the various contracts included in Traitify:
π οΈ Builder
Contract
Example:
class PostBuilder implements CleaniqueCoders\Traitify\Contracts\Builder
{
public function build(): self
{
// Build logic here
return $this;
}
}
π Execute
Contract
Example:
class PostExecutor implements CleaniqueCoders\Traitify\Contracts\Execute
{
public function execute(): self
{
// Execution logic here
return $this;
}
}
π Menu
Contract
Example:
class PostMenu implements CleaniqueCoders\Traitify\Contracts\Menu
{
public function menus(): \Illuminate\Support\Collection
{
return collect([
['name' => 'Home', 'url' => '/'],
['name' => 'Posts', 'url' => '/posts']
]);
}
}
π Processor
Contract
Example:
class PostProcessor implements CleaniqueCoders\Traitify\Contracts\Processor
{
public function process(): self
{
// Process logic here
return $this;
}
}
π Get Started Today!
Head over to https://github.com/cleaniquecoders/traitify, install it, and start writing cleaner, more maintainable Laravel applications today!
If you find it useful or have any feedback, feel free to reach out! Letβs build something amazing together. β¨
π Share the Love:
If you like Traitify, share it with your community and friends. Letβs spread the word and build better apps together! π»π
Posted on October 15, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.