PHPackages                             mkamelmasoud/starter-core-kit - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. mkamelmasoud/starter-core-kit

ActiveLibrary[Framework](/categories/framework)

mkamelmasoud/starter-core-kit
=============================

A reusable Laravel starter kit for custom exception handling, middleware, and shared utilities.

1.4.0(6mo ago)0881MITPHPPHP ^8.1

Since Oct 18Pushed 6mo agoCompare

[ Source](https://github.com/Coder0010/starter-core-kit)[ Packagist](https://packagist.org/packages/mkamelmasoud/starter-core-kit)[ RSS](/packages/mkamelmasoud-starter-core-kit/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (10)Versions (6)Used By (0)

🚀 Starter Core Kit for Laravel
==============================

[](#-starter-core-kit-for-laravel)

A comprehensive, production-ready Laravel starter package that provides essential utilities, middleware, exception handling, AI integration, and repository patterns for modern Laravel applications.

[![Latest Version](https://camo.githubusercontent.com/f3056f4b9cbeff16de179a16570836e488483b66277faff569ce2d9e00326f5d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6b616d656c6d61736f75642f737461727465722d636f72652d6b69742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mkamelmasoud/starter-core-kit)[![Total Downloads](https://camo.githubusercontent.com/2ca8358fcbefed64f02ef30d2de6fcc66898043940bf9253cd5e5010c429b184/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6b616d656c6d61736f75642f737461727465722d636f72652d6b69742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mkamelmasoud/starter-core-kit)[![License](https://camo.githubusercontent.com/1f45d0cf730e7a66902d258506f7f8dd1e5eda9e542e3d95e139d6420f481566/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d6b616d656c6d61736f75642f737461727465722d636f72652d6b69742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mkamelmasoud/starter-core-kit)

---

✨ Features
----------

[](#-features)

### 🛡️ Exception Handling &amp; Middleware

[](#️-exception-handling--middleware)

- **Custom Global Exception Handler** - Centralized exception handling with JSON responses
- **API Header Validation Middleware** - Ensures proper API request headers
- **Dynamic Locale Middleware** - Automatic locale detection from headers
- **Multi-language Exception Messages** - Localized error messages (English/Arabic)
- **Comprehensive Exception Mapping** - Pre-configured responses for common Laravel exceptions

### 🤖 AI Integration

[](#-ai-integration)

- **Multi-Provider AI Support** - OpenAI and Router.ai integration
- **Simple Factory Pattern** - Clean provider instantiation
- **AI Client Service** - Easy-to-use interface for AI interactions
- **Built-in Caching** - Automatic response caching with TTL
- **Comprehensive Logging** - Detailed request/response logging

### 🏗️ Repository &amp; Service Patterns

[](#️-repository--service-patterns)

- **Base Repository Pattern** - Eloquent-based repository implementation
- **Base Service Layer** - Service layer with caching and transaction support
- **CRUD Operations** - Complete Create, Read, Update, Delete functionality
- **Advanced Query Building** - Flexible filtering and data fetching
- **Caching Support** - Built-in caching with TTL configuration

### 🔧 Utilities &amp; Helpers

[](#-utilities--helpers)

- **API Response Traits** - Standardized JSON response formatting
- **File Upload Handling** - Secure file upload utilities
- **Cache Management** - Advanced caching with automatic invalidation
- **Helper Functions** - Utility functions for common operations
- **Validation Rules** - Custom validation rules (e.g., NoHtmlRule)

### 📊 Data Management

[](#-data-management)

- **Pagination Support** - Built-in pagination for large datasets
- **Search Functionality** - Advanced search capabilities
- **Random Data Fetching** - Random record selection
- **Relationship Loading** - Eager loading with relationship support
- **Soft Delete Support** - Soft delete functionality

---

📁 Project Structure
-------------------

[](#-project-structure)

```
starter-core-kit/
+---src
|   PackageServiceProvider.php
|
+---Contracts
|   |   AiProviderContract.php
|   |   MiddlewareContract.php
|   |   ServiceContract.php
|   |   SortableContract.php
|   |
|   \---Repositories
|           BaseRepositoryContract.php
|           DeletableRepositoryContract.php
|           ReadableRepositoryContract.php
|           WritableRepositoryContract.php
|
+---Core
|   |   BaseDto.php
|   |   BaseEntity.php
|   |   BaseService.php
|   |
|   +---Ai
|   |   |   BaseAIProvider.php
|   |   |
|   |   \---Traits
|   |           BuildRequestTrait.php
|   |           HandlesValidationTrait.php
|   |           ManageStateTrait.php
|   |
|   +---Repositories
|   |   |   BaseEloquentRepository.php
|   |   |
|   |   \---Traits
|   |           BuildQueryTrait.php
|   |
|   \---Services
|       \---Traits
|               DeletableServiceTrait.php
|               ReadableServiceTrait.php
|               WritableServiceTrait.php
|
+---Exceptions
|       AiConfigNotFoundException.php
|       AiProviderNotFoundException.php
|       Handler.php
|
+---lang
|   +---ar
|   |       exceptions.php
|   |
|   \---en
|           exceptions.php
|
+---Middleware
|       ApiCheckHeadersMiddleware.php
|       ClearLoggerMiddleware.php
|       SetLocaleFromHeaderMiddleware.php
|
+---Providers
|       ConfigServiceProvider.php
|       ExceptionServiceProvider.php
|       MacroServiceProvider.php
|       MiddlewareServiceProvider.php
|       RepositoryServiceProvider.php
|       ResourceServiceProvider.php
|       SupportServiceProvider.php
|
+---Rules
|   \---Validation
|           NoHtmlRule.php
|
+---Services
|   \---Ai
|       |   AiClientService.php
|       |
|       +---AiProviders
|       |       OpenAiProviderService.php
|       |       RouterAiProviderService.php
|       |
|       \---Providers
+---Support
|   +---Factories
|   |       AiClientFactory.php
|   |
|   \---helpers
|           functions.php
|
\---Traits
    +---Api
    |       ApiResponsesTrait.php
    |
    +---File
    |       HandleFileUploadTrait.php
    |
    +---Service
    |       ServiceSupportTrait.php
    |
    \---Support
            SupportCacheTrait.php
            SupportSortableTrait.php

```

---

📦 Installation
--------------

[](#-installation)

Install the package via Composer:

```
composer require mkamelmasoud/starter-core-kit
```

The package will automatically register its service provider.

---

⚙️ Configuration
----------------

[](#️-configuration)

Publish the configuration files:

```
php artisan vendor:publish --tag=starter-core-kit
```

This will publish:

- `config/starter-core-kit.php` - Main configuration
- `config/repositories.php` - Repository configuration
- `lang/vendor/starter-core-kit/` - Language files

---

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Basic AI Usage

[](#1-basic-ai-usage)

```
use MkamelMasoud\StarterCoreKit\Services\Ai\AiClientService;

// AI Integration - Simple usage
$aiClient = app('ai-client');
$response = $aiClient->ask('Hello, how are you?');

// With system prompt
$aiClient->setPrompt('system', 'You are a helpful assistant');
$response = $aiClient->ask('Write a poem about coding');

// Using specific provider
$aiClient = new AiClientService('openai');
$response = $aiClient->ask('Explain Laravel');
```

### 2. Repository Pattern

[](#2-repository-pattern)

```
use MkamelMasoud\StarterCoreKit\Core\Repositories\BaseEloquentRepository;

class UserRepository extends BaseEloquentRepository
{
    protected function entity(): string
    {
        return User::class;
    }
}
```

### 3. Service Layer

[](#3-service-layer)

```
use MkamelMasoud\StarterCoreKit\Core\BaseService;

class UserService extends BaseService
{
    protected function getDtoClass(): string
    {
        return UserDto::class;
    }

    protected function getRepoClass(): string
    {
        return UserRepository::class;
    }
}
```

### 4. API Responses

[](#4-api-responses)

```
use MkamelMasoud\StarterCoreKit\Traits\Api\ApiResponsesTrait;

class UserController extends Controller
{
    use ApiResponsesTrait;

    public function index()
    {
        $users = User::all();
        return $this->success('Users retrieved successfully', $users);
    }
}
```

---

🔧 Configuration Options
-----------------------

[](#-configuration-options)

### Main Configuration (`config/starter-core-kit.php`)

[](#main-configuration-configstarter-core-kitphp)

```
return [
    'version' => '1.0.0',
    'supported_locales' => ['en', 'ar'],

    'middlewares' => [
        'set_locale' => env('SET_LOCALE', true),
        'clear_logger' => env('CLEAR_LOGGER', false),
        'api_check_headers' => env('API_CHECK_HEADERS', true),
    ],

    'cache_results' => [
        'enabled' => env('APP_CACHE_RESULTS_ENABLED', false),
        'ttl' => env('APP_CACHE_RESULTS_TTL', 1),
    ],

    'ai' => [
        'enabled' => env('AI_ENABLED', true),
        'default' => env('AI_PROVIDER', 'openai'),
        'fallback' => env('AI_PROVIDER_FALLBACK', 'router'),

        'cache' => [
            'enabled' => env('AI_CACHE_ENABLED', true),
            'ttl' => env('AI_CACHE_TTL', 600),
        ],

        'timeout' => env('AI_PROVIDER_TIMEOUT', 20),
        'retry' => [
            'attempts' => env('AI_PROVIDER_RETRY_ATTEMPTS', 2),
            'delay' => env('AI_PROVIDER_RETRY_DELAY_MS', 500),
        ],

        'logging' => [
            'enabled' => env('AI_PROVIDER_LOGGING_ENABLED', true),
        ],

        'providers' => [
            'openai' => [
                'api_key' => env('OPENAI_API_KEY'),
                'base_url' => env('OPENAI_BASEURL', 'https://api.openai.com'),
                'version' => env('OPENAI_VERSION', 'v1'),
                'end_point' => env('OPENAI_ENDPOINT', 'chat/completions'),
                'model' => env('OPENAI_MODEL', 'gpt-4o-mini'),
            ],
            'router' => [
                'api_key' => env('ROUTER_API_KEY'),
                'base_url' => env('ROUTER_BASEURL', 'https://openrouter.ai/api'),
                'version' => env('ROUTER_VERSION', 'v1'),
                'end_point' => env('ROUTER_ENDPOINT', 'chat/completions'),
                'model' => env('ROUTER_MODEL', 'gpt-4o-mini'),
            ],
        ],
    ],
];
```

### Environment Variables

[](#environment-variables)

```
# AI Configuration
AI_ENABLED=true
AI_PROVIDER=openai
AI_PROVIDER_FALLBACK=router

# OpenAI Configuration
OPENAI_API_KEY=your_openai_key
OPENAI_BASEURL=https://api.openai.com
OPENAI_VERSION=v1
OPENAI_ENDPOINT=chat/completions
OPENAI_MODEL=gpt-4o-mini

# Router Configuration
ROUTER_API_KEY=your_router_key
ROUTER_BASEURL=https://openrouter.ai/api
ROUTER_VERSION=v1
ROUTER_ENDPOINT=chat/completions
ROUTER_MODEL=gpt-4o-mini

# AI Cache Configuration
AI_CACHE_ENABLED=true
AI_CACHE_TTL=600

# AI Request Configuration
AI_PROVIDER_TIMEOUT=20
AI_PROVIDER_RETRY_ATTEMPTS=2
AI_PROVIDER_RETRY_DELAY_MS=500
AI_PROVIDER_LOGGING_ENABLED=true

# Middleware Configuration
SET_LOCALE=true
CLEAR_LOGGER=false
API_CHECK_HEADERS=true

# Cache Configuration
APP_CACHE_RESULTS_ENABLED=false
APP_CACHE_RESULTS_TTL=1
```

---

🛠️ Advanced Usage
-----------------

[](#️-advanced-usage)

### Custom Exception Handling

[](#custom-exception-handling)

The package provides comprehensive exception handling for common Laravel exceptions:

- `ModelNotFoundException` → 404 Not Found
- `NotFoundHttpException` → 404 Not Found
- `MethodNotAllowedHttpException` → 405 Method Not Allowed
- `ValidationException` → 422 Unprocessable Entity
- `AuthorizationException` → 401 Unauthorized
- `AuthenticationException` → 403 Forbidden
- `ThrottleRequestsException` → 429 Too Many Requests
- And many more...

### Middleware Usage

[](#middleware-usage)

```
// In your routes/web.php or routes/api.php
Route::middleware(['api', 'starter-core-kit.api-headers'])->group(function () {
    // Your API routes
});

Route::middleware(['starter-core-kit.locale'])->group(function () {
    // Routes that need locale detection
});
```

### Repository Advanced Features

[](#repository-advanced-features)

```
// Advanced query building
$users = $userRepository
    ->where('status', '=', 'active')
    ->where('age', '>', 18)
    ->with(['profile', 'posts'])
    ->fetchData(['status' => 'active'], 'paginate', 20);

// Search functionality
$results = $userService->search(['name' => ['John', 'Jane']]);

// Random records
$randomUsers = $userService->inRandomOrder(5);
```

### Caching Features

[](#caching-features)

```
// Automatic caching with TTL
$users = $userService->fetchData(
    filters: ['status' => 'active'],
    cachePrefix: 'active_users'
);

// Manual cache management
$userService->clearCache('users');
```

---

🌍 Internationalization
----------------------

[](#-internationalization)

The package supports multiple languages out of the box:

- **English** (en) - Default
- **Arabic** (ar) - RTL support

Add more languages by extending the language files in `lang/vendor/starter-core-kit/`.

---

🧪 Testing
---------

[](#-testing)

Run the test suite:

```
composer test
```

Run code quality checks:

```
composer phpstan
composer pint
```

---

📚 API Documentation
-------------------

[](#-api-documentation)

### AI Client Service

[](#ai-client-service)

```
// Basic usage
$response = app('ai-client')->ask('Your prompt here');

// With system prompt
$aiClient = app('ai-client');
$aiClient->setPrompt('system', 'You are a helpful assistant');
$response = $aiClient->ask('Your prompt');

// Using specific provider
$aiClient = new AiClientService('openai');
$response = $aiClient->ask('Your prompt');

// Advanced usage with configuration
$aiClient = new AiClientService('router');
$aiClient->setPrompt('system', 'You are a coding expert');
$response = $aiClient->ask('Explain Laravel middleware');
```

### Repository Methods

[](#repository-methods)

```
// Fetch data with filters
$data = $repository->fetchData(
    filters: ['status' => 'active'],
    dataTypeReturn: 'paginate', // 'get', 'builder', 'paginate'
    limit: 20,
    random: false
);

// Find single record
$user = $repository->find(1);

// Find multiple records
$users = $repository->findMany([1, 2, 3]);

// CRUD operations
$user = $repository->store($data);
$user = $repository->update(1, $data);
$repository->delete(1);
```

### Service Layer Methods

[](#service-layer-methods)

```
// Data fetching with caching
$users = $userService->fetchData(['status' => 'active']);

// Search functionality
$results = $userService->search(['name' => ['John']]);

// Random records
$randomUsers = $userService->inRandomOrder(5);

// CRUD with DTOs
$user = $userService->store($userDto);
$user = $userService->update(1, $userDto);
$userService->delete(1, 'soft'); // or 'force'
```

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

---

📄 License
---------

[](#-license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

🙏 Acknowledgments
-----------------

[](#-acknowledgments)

- Laravel Framework
- OpenAI API
- OpenRouter API
- The Laravel community

---

📞 Support
---------

[](#-support)

- **Issues**: [GitHub Issues](https://github.com/coder0010/starter-core-kit/issues)
- **Documentation**: [GitHub Repository](https://github.com/coder0010/starter-core-kit)
- **Email**:

---

**Made with ❤️ by [Mostafa Kamel](https://github.com/coder0010)**

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance66

Regular maintenance activity

Popularity16

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~14 days

Total

5

Last Release

201d ago

PHP version history (2 changes)1.0.0PHP &gt;=8.0 &lt;8.6

1.2.0PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/36075001?v=4)[Mostafa.Kamel.Masoud](/maintainers/mkamel-93)[@mkamel-93](https://github.com/mkamel-93)

---

Top Contributors

[![mkamel-93](https://avatars.githubusercontent.com/u/36075001?v=4)](https://github.com/mkamel-93 "mkamel-93 (8 commits)")

---

Tags

middlewarelaravelpackageutilitiesexception handlerstarter-kitcore-kit

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mkamelmasoud-starter-core-kit/health.svg)

```
[![Health](https://phpackages.com/badges/mkamelmasoud-starter-core-kit/health.svg)](https://phpackages.com/packages/mkamelmasoud-starter-core-kit)
```

###  Alternatives

[laravel/horizon

Dashboard and code-driven configuration for Laravel queues.

4.2k95.4M299](/packages/laravel-horizon)[laravel/sail

Docker files for running a basic Laravel application.

1.9k205.7M1.3k](/packages/laravel-sail)[laravel/socialite

Laravel wrapper around OAuth 1 &amp; OAuth 2 libraries.

5.7k108.5M874](/packages/laravel-socialite)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M187](/packages/laravel-ai)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M145](/packages/laravel-mcp)[laravel/surveyor

Static analysis tool for Laravel applications.

86121.4k11](/packages/laravel-surveyor)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
