PHP code example of elegantmedia / laravel-simple-repository

1. Go to this page and download the library: Download elegantmedia/laravel-simple-repository 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/ */

    

elegantmedia / laravel-simple-repository example snippets


// All Laravel query builder methods are available
$filter = $repository->newFilter()
    ->where('status', 'active')
    ->whereIn('role', ['admin', 'moderator'])
    ->whereHas('posts', function ($query) {
        $query->where('published', true);
    })
    ->with(['profile', 'posts'])
    ->orderBy('created_at', 'desc')
    ->select('id', 'name', 'email');

// Create a filter with date conditions
$filter = $repository->newFilter()
    ->whereDateThisMonth()
    ->whereDateInThisFinancialYear('revenue_date')
    ->where('status', 'active')
    ->orderBy('created_at', 'desc');

// Apply the filter
$results = $repository->search($filter);

// newModel() - Create a new model instance without saving
$user = $repository->newModel();
$user->name = 'John Doe';
$user->email = '[email protected]';
$repository->save($user);

// newQuery() - Get a query builder for complex operations
$query = $repository->newQuery()
    ->where('active', true)
    ->whereYear('created_at', 2024);
$count = $query->count();

// newFilter() - Create a reusable filter
$activeUsersFilter = $repository->newFilter()
    ->where('status', 'active')
    ->where('verified', true);

// Example: Building a reusable filter for search operations
$filter = $repository->newFilter()
    ->setKeyword('Laravel')
    ->where('status', 'active')
    ->whereIn('category', ['tutorial', 'guide'])
    ->whereDateThisMonth()
    ->setSortBy('views')
    ->setSortDirection('desc')
    ->setPaginate(true)
    ->setPerPage(20);

// Use the filter with repository methods
$results = $repository->search($filter);  // Returns paginated results
$allResults = $repository->paginate(50, [], $filter);  // Custom pagination

// Example: Direct query builder for custom operations
$query = $repository->newQuery()
    ->select('department', DB::raw('COUNT(*) as total'))
    ->where('active', true)
    ->groupBy('department')
    ->having('total', '>', 10);

$departments = $query->get();

// Example: Complex join operation
$results = $repository->newQuery()
    ->join('posts', 'users.id', '=', 'posts.user_id')
    ->where('posts.published', true)
    ->whereYear('posts.created_at', 2024)
    ->select('users.*', DB::raw('COUNT(posts.id) as post_count'))
    ->groupBy('users.id')
    ->orderBy('post_count', 'desc')
    ->limit(10)
    ->get();

// paginate() - Standard Laravel pagination with total count
$users = $repository->paginate(20); // 20 items per page
$users = $repository->paginate(20, ['profile', 'posts']); // With eager loading
$users = $repository->paginate(20, [], $filter); // With custom filter

// simplePaginate() - More efficient pagination without total count
$users = $repository->simplePaginate(50); // Faster for large datasets
$users = $repository->simplePaginate(50, ['profile']); // With relations

// search() - Flexible search that respects filter's pagination setting
$filter = $repository->newFilter()
    ->setKeyword('john')
    ->setPaginate(true)
    ->setPerPage(20);
$results = $repository->search($filter); // Returns LengthAwarePaginator

$filter->setPaginate(false);
$results = $repository->search($filter); // Returns Collection

// searchByTerm() - Simple search returning all results
$users = $repository->searchByTerm('[email protected]'); // Returns Collection
// Good for autocomplete, dropdowns, or small result sets

// searchPaginated() - Always returns paginated results
$results = $repository->searchPaginated('john', 25); // 25 per page
$results = $repository->searchPaginated('admin', 10); // 10 per page
// Perfect for search results pages, data tables

// updateModel() - Update an existing model instance
$user = $repository->find(1);
$updated = $repository->updateModel($user, [
    'name' => 'Jane Doe',
    'email' => '[email protected]'
]);

// updateById() - Update without fetching the model first
$updated = $repository->updateById(1, [
    'last_login' => now(),
    'login_count' => DB::raw('login_count + 1')
]);

// updateWhere() - Bulk update with conditions
$affectedRows = $repository->updateWhere(
    ['status' => 'pending', 'created_at' => '<', now()->subDays(7)],
    ['status' => 'expired']
);

// sum() - Calculate sum of a column
$totalRevenue = $repository->sum('revenue');
$monthlyRevenue = $repository->sum('revenue', [
    'created_at' => '>=', now()->startOfMonth()
]);

// avg() - Calculate average
$averagePrice = $repository->avg('price');
$averageRating = $repository->avg('rating', ['status' => 'published']);

// min() - Get minimum value
$lowestPrice = $repository->min('price');
$earliestDate = $repository->min('created_at', ['status' => 'active']);

// exists() - Check if records exist
if ($repository->exists(['email' => '[email protected]'])) {
    // Email already taken
}

// value() - Get a single column value
$userName = $repository->value('name', ['id' => 1]);
$latestLogin = $repository->value('last_login', ['email' => '[email protected]']);

// pluck() - Get array of values
$names = $repository->pluck('name'); // Collection of all names
$emailsByName = $repository->pluck('email', [], 'name'); // Keyed by name
$activeEmails = $repository->pluck('email', ['status' => 'active']);

// chunk() - Process large datasets efficiently
$repository->chunk(1000, function ($users) {
    foreach ($users as $user) {
        // Process each user
        Mail::to($user)->send(new Newsletter());
    }
}, ['subscribed' => true]);

// random() - Get random records
$randomUser = $repository->random(); // Single random model
$randomUsers = $repository->random(5); // Collection of 5 random models

// withTransaction() - Enable automatic transactions
$repository->withTransaction(); // Enable
$user = $repository->create(['name' => 'John']); // Wrapped in transaction
$repository->updateModel($user, ['verified' => true]); // Also wrapped
$repository->withTransaction(false); // Disable

// transaction() - Callback-based transactions
$result = $repository->transaction(function ($repo) {
    $user = $repo->create(['name' => 'Jane']);
    $profile = $repo->create(['user_id' => $user->id]);
    
    if (!$user->isValid()) {
        throw new \Exception('Invalid user');
    }
    
    return $user;
}); // Automatically rolled back on exception

// setKeyword() - Search in model's searchable fields
$filter = $repository->newFilter()
    ->setKeyword('john doe'); // Searches in fields defined by model

// setSortBy() and setSortDirection()
$filter->setSortBy('created_at')
    ->setSortDirection('desc'); // Latest first

// setPaginate() - Control pagination behavior
$filter->setPaginate(true); // Enable pagination
$filter->setPaginate(false); // Disable - returns all results

// setPerPage() - Control page size
$filter->setPerPage(100); // Max 100 items per page
$filter->setPerPage(10); // 10 items per page

use Carbon\Carbon;
use Carbon\CarbonPeriod;

// whereDateIs() - Exact date match
$filter = $repository->newFilter()
    ->whereDateIs(Carbon::parse('2024-01-15')); // All records from Jan 15, 2024

// whereDateInPeriod() - Using Carbon periods
$period = CarbonPeriod::create('2024-01-01', '2024-01-31');
$filter = $repository->newFilter()
    ->whereDateInPeriod($period); // All January 2024 records

// Custom column filtering
$filter = $repository->newFilter()
    ->whereDateIs(Carbon::today(), 'published_at')
    ->whereDateInPeriod($period, 'approved_at');

return [
    'defaults' => [
        'pagination' => [
            'per_page' => 50,
            'max_per_page' => 100,
        ],
        'sorting' => [
            'field' => 'created_at',
            'direction' => 'desc',
        ],
    ],
    'search' => [
        'query_parameter' => 'q',
        'case_sensitive' => false,
    ],
    'command' => [
        'directory' => 'Models',
        'suffix' => 'Repository',
    ],
];



namespace App\Http\Controllers;

use App\Models\UsersRepository;

class UserController extends Controller
{
    public function __construct(
        private UsersRepository $users
    ) {}

    public function index()
    {
        return $this->users->paginate(20);
    }

    public function show(int $id)
    {
        return $this->users->findOrFail($id);
    }
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use ElegantMedia\SimpleRepository\Search\Traits\SearchableLike;

class User extends Model
{
    use SearchableLike;

    protected array $searchable = [
        'name',
        'email',
    ];
}

$filter = $repository->newFilter()
    ->where('status', 'active')
    ->with(['posts', 'comments'])
    ->setSortBy('created_at');

$users = $repository->search($filter);
bash
php artisan vendor:publish --provider="ElegantMedia\SimpleRepository\SimpleRepositoryServiceProvider" --tag="simple-repository-config"
bash
php artisan make:repository User