PHP code example of twenycode / laravel-blueprint

1. Go to this page and download the library: Download twenycode/laravel-blueprint library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

twenycode / laravel-blueprint example snippets


<!-- Before closing </body> tag -->
@

// Display a success message
$this->successMsg('Operation completed successfully');

// Display an error message
$this->errorMsg('Something went wrong');

// Redirect with a success message
return $this->success('Changes saved');

// Redirect to a route with a success message
return $this->successRoute('users.index', 'User created successfully');

// Redirect with an error message
return $this->error('Operation failed');

// Redirect to a route with an error message
return $this->errorRoute('users.index', 'User could not be created');



namespace App\Repositories;

use App\Models\User;
use TwenyCode\LaravelBlueprint\Repositories\BaseRepository;

class UserRepository extends BaseRepository
{
    public function __construct(User $model)
    {
        parent::__construct($model);
        
        // Define default relationships to eager load
        $this->relationships = ['roles', 'permissions'];
    }
    
    // Add custom repository methods
    public function findByEmail(string $email)
    {
        return $this->handleError(function () use ($email) {
            return $this->model->where('email', $email)->first();
        }, 'find user by email');
    }
}



namespace App\Services;

use App\Repositories\UserRepository;
use TwenyCode\LaravelBlueprint\Services\BaseService;
use Illuminate\Support\Facades\Hash;

class UserService extends BaseService
{
    public function __construct(UserRepository $repository)
    {
        parent::__construct($repository);
    }
    
    // Add custom business logic
    public function registerUser(array $data)
    {
        return $this->transaction(function () use ($data) {
            // Process data and create user
            $data['password'] = Hash::make($data['password']);
            return $this->repository->create($data);
        });
    }
}



namespace App\Http\Controllers;

use App\Http\Requests\UserStoreRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Services\UserService;
use TwenyCode\LaravelBlueprint\Controllers\BaseResourceController;

class UserController extends BaseResourceController
{
    public function __construct(UserService $service)
    {
        $this->layer = $service;
        $this->controllerName = 'User';
        $this->baseViewName = 'users';
        $this->baseRouteName = 'users';
        $this->resourceVariable = 'user';
        $this->hasRelationShips = true;
    }
    
    public function store(UserStoreRequest $request)
    {
        return $this->processStore($request);
    }
    
    public function update(UserUpdateRequest $request, $id)
    {
        return $this->processUpdate($request, $id);
    }
}



namespace App\Http\Controllers\Api;

use App\Http\Requests\UserStoreRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Services\UserService;
use TwenyCode\LaravelBlueprint\Controllers\BaseApiResourceController;

class UserController extends BaseApiResourceController
{
    public function __construct(UserService $service)
    {
        $this->layer = $service;
        $this->controllerName = 'User';
        $this->baseRouteName = 'users';
        $this->resourceVariable = 'user';
        $this->hasRelationShips = true;
    }
    
    public function store(UserStoreRequest $request)
    {
        return $this->processStore($request);
    }
    
    public function update(UserUpdateRequest $request, $id)
    {
        return $this->processUpdate($request, $id);
    }
}



namespace App\Models;

use TwenyCode\LaravelBlueprint\Models\BaseModel;

class User extends BaseModel
{
    protected $fillable = [
        'name', 'email', 'password',
    ];
    
    protected $hidden = [
        'password', 'remember_token',
    ];
    
    // Add custom relationships, methods, etc.
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}



namespace App\Http\Requests;

use TwenyCode\LaravelBlueprint\Http\Requests\BaseFormRequest;

class UserStoreRequest extends BaseFormRequest
{
    public function authorize()
    {
        return $this->checkPermission('create-user');
    }
    
    public function rules()
    {
        return [
            'name' => '



namespace App\Http\Requests;

use TwenyCode\LaravelBlueprint\Http\Requests\BaseFormRequest;
use TwenyCode\LaravelBlueprint\Rules\CompositeKeyUniquenessChecker;

class ProjectMemberRequest extends BaseFormRequest
{
    public function rules()
    {
        return [
            'user_id' => [
                '('id') // For updates
                )
            ],
        ];
    }
}

// Convert date formats
$formattedDate = dateTimeConversion('2023-01-01', 'd M Y');  // "01 Jan 2023"

// Calculate days between dates
$daysBetween = numberOfDays('2023-01-01', '2023-01-15');  // 14

// Calculate age in days
$age = calculateAge('1990-01-01');  // Age in days

// Get human-readable date difference
$diff = dateDifference('2023-01-01', '2023-02-01');  // "1 months"

// Calculate remaining days
$remaining = calculateRemainingDays('2023-12-31');  // Days until date

// Format time ago
$timeAgo = formatTimeAgo('2023-01-01 12:00:00');  // "3 months ago"

// Format date ranges
$range = formatDateDuration('2023-01-15', '2023-02-20');  // "15 Jan - 20 Feb, 2023"

// Format file sizes
$fileSize = formatFileSize(1024 * 1024);  // "1.00 MB"

// Format currency
$amount = formatCurrencyDecimal(1234.56);  // "1,234.56"
$rounded = formatCurrency(1234.56);  // "1,235"
$money = formatMoney(1234.56);  // "$ 1,234.56"

// Calculate percentages
$value = calculatePercentNumber(15, 200);  // 30

// Manipulate strings
$withoutUnderscores = removeUnderscore('hello_world');  // "hello world"
$withUnderscores = addUnderscore('hello world');  // "hello_world"
$snakeCase = snake('HelloWorld');  // "hello_world"
$headlined = headline('user_profile_settings');  // "User Profile Settings"

// Work with plurals
$plural = pluralize('category');  // "categories"
$pluralVar = pluralizeVariableName('userProfile');  // "userProfiles"

// Handle pluralization
$suffix = plural(1);  // ""
$suffix = plural(2);  // "s"

// Trim text
$trimmed = trimWords('This is a long text that needs trimming', 5);  // "This is a long text..."
$trimmedHtml = trimHtmlWords('<p>This is a <strong>long</strong> text</p>', 3);  // "<p>This is a...</p>"

// Repository methods are automatically cached
$users = $userRepository->getAll();  // Cached for 24 hours by default

// Customize cache duration
$users = $userRepository->setCacheDuration(60)->getAll();  // Cache for 1 hour

// Clear cache manually
$userRepository->clearCacheKey();

// Forget specific cache keys
$userRepository->forgetCache(['all', 'active']);



namespace App\Repositories;

use TwenyCode\LaravelBlueprint\Repositories\BaseRepository;
use TwenyCode\LaravelBlueprint\Traits\EventCacheTrait;

class EventRepository extends BaseRepository
{
    use EventCacheTrait;
    
    public function getUpcomingEvents()
    {
        return $this->rememberEventCache('upcoming', function() {
            return $this->model->where('start_date', '>', now())->get();
        });
    }
}

// In config/tweny-blueprint.php
'observable_models' => [
    \App\Models\User::class,
    \App\Models\Product::class,
],

// Cache is automatically cleared when models are created, updated, or deleted

// Enable/disable model cache observers
'enable_cache_observers' => true,

// Common cache keys
'cache_keys' => [
    'all', 'with_relationship', 'active_with_relationship', 
    'inactive_with_relationship', 'trashed', 'paginated', 'active', 'pluck_active'
],

// Default cache duration in minutes
'cache_duration' => 1440, // 24 hours

'connections' => [
    'main' => [
        'salt' => env('HASHIDS_SALT', config('app.key')),
        'length' => 6,
        'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
    ],
],

// Observable models (automatically clear cache on changes)
'observable_models' => [
    \App\Models\User::class,
    \App\Models\Product::class,
],

// User-specific cache models (for per-user data)
'user_cache_models' => [
    'Contract', 'Task', 'Project'
],

// Whether to check authorization by default in controllers
'check_authorization' => true,

// Super admin role name
'super_admin_role' => 'superAdmin',

// In repositories, services, and controllers
protected function handleError(callable $function, string $context, mixed $request = null, string $msg = 'Something went wrong')
{
    try {
        return $function();
    } catch (Exception $e) {
        // Automatic logging and graceful error handling
        Log::error("Failed to {$context}: " . $e->getMessage());
        
        // Return appropriate response based on context
        if (method_exists($this, 'error')) {
            return $this->error($msg);
        }
        
        throw $e;
    }
}

public function findActiveByEmail($email)
{
    return $this->handleError(function () use ($email) {
        return $this->model
            ->where('email', $email)
            ->where('is_active', true)
            ->first();
    }, 'find active user by email');
}

public function getPopularUsers($limit = 10)
{
    return $this->handleError(function () use ($limit) {
        return $this->model
            ->withCount('posts')
            ->orderBy('posts_count', 'desc')
            ->limit($limit)
            ->get();
    }, 'get popular users');
}

public function registerUser(array $data)
{
    return $this->transaction(function () use ($data) {
        // Create user
        $user = $this->repository->create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        
        // Assign role
        $user->assignRole('user');
        
        // Send welcome email
        Mail::to($user->email)->send(new WelcomeEmail($user));
        
        return $user;
    });
}

public function bulkUpdateStatus(array $userIds, bool $status)
{
    return $this->transaction(function () use ($userIds, $status) {
        foreach ($userIds as $userId) {
            $this->repository->update($userId, ['is_active' => $status]);
        }
        return count($userIds);
    });
}



namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use App\Repositories\UserRepository;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserRepositoryTest extends TestCase
{
    use RefreshDatabase;
    
    public function test_can_create_user()
    {
        $repository = new UserRepository(new User());
        
        $userData = [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => 'password123',
        ];
        
        $user = $repository->create($userData);
        
        $this->assertInstanceOf(User::class, $user);
        $this->assertEquals('John Doe', $user->name);
        $this->assertDatabaseHas('users', ['email' => '[email protected]']);
    }
    
    public function test_can_find_active_users()
    {
        User::factory()->count(3)->create(['is_active' => true]);
        User::factory()->count(2)->create(['is_active' => false]);
        
        $repository = new UserRepository(new User());
        $activeUsers = $repository->getActiveData();
        
        $this->assertCount(3, $activeUsers);
    }
}

// Log cache operations
Log::info('Cache hit for key: ' . $cacheKey);

// Monitor query counts
DB::enableQueryLog();
// ... your operations
$queries = DB::getQueryLog();
Log::info('Query count: ' . count($queries));
bash
php artisan vendor:publish --provider="TwenyCode\LaravelBlueprint\TwenyLaravelBlueprintServiceProvider" --tag="tcb-config"
bash
php artisan vendor:publish --provider="RealRashid\SweetAlert\SweetAlertServiceProvider" --tag=sweetalert-config