### Install Laravel Helpers via Composer Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Use this command to add the package to your Laravel project. ```bash composer require achyutn/laravel-helpers ``` -------------------------------- ### Slim Pagination Format with CustomPaginator Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt This package automatically replaces Laravel's default LengthAwarePaginator serialization with a slimmer format. No code changes are required after installation; all `paginate()` calls will use this format. ```php // No code change needed — works automatically after package installation. // Any paginate() call returns the custom format: $posts = Post::paginate(10); return response()->json($posts); // Response shape: // { // "data": [ { "id": 1, "title": "..." }, ... ], // "total": 42, // "perPage": 10, // "page": 1 // } // Compare to Laravel default which includes: first_page_url, last_page_url, // next_page_url, prev_page_url, links, from, to, last_page, path, etc. ``` -------------------------------- ### Setup CanBeInactive Trait Schema Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Ensure your model's table includes an 'inactive_at' timestamp column before using the CanBeInactive trait. ```php Schema::table('articles', function (Blueprint $table) { $table->timestamp('inactive_at')->nullable(); }); ``` -------------------------------- ### Define Multiple Media Collections Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Configure multiple media collections in your model by setting the $theMediaCollections property. Access collections using dedicated methods. ```php namespace App\Models; use AchyutN\LaravelHelpers\Models\MediaModel; class Post extends MediaModel { protected array $theMediaCollections = ['cover', 'gallery', 'profile']; } ``` ```php $post = Post::find(1); echo $post->gallery(); // Gallery collection image echo $post->big_gallery(); // Large gallery image echo $post->profile(); // Profile collection image echo $post->medium_profile(); // Medium profile image ``` -------------------------------- ### HasTheMedia Trait for Image Conversions Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Integrates Spatie Media Library with pre-configured WebP image conversion sizes. Supports multiple named media collections and provides magic accessor methods for converted URLs. ```php addMedia('/path/to/image.jpg')->toMediaCollection('cover'); $post->addMedia('/path/to/photo.jpg')->toMediaCollection('gallery'); // Retrieve converted URLs: echo $post->cover(); // Original WebP URL for 'cover' collection echo $post->small_cover(); // 150×80 WebP URL echo $post->medium_cover(); // 300×160 WebP URL echo $post->big_cover(); // 800×420 WebP URL echo $post->gallery(); // Original WebP URL for 'gallery' collection echo $post->medium_gallery(); // 300×160 WebP URL for 'gallery' echo $post->avatar(); // Original WebP URL for 'avatar' collection // Returns null if no media is attached to the collection var_dump($post->small_avatar()); // NULL ``` -------------------------------- ### Use HasTheMedia Trait for Media Handling Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Extend your model with the HasTheMedia trait to leverage spatie/laravel-medialibrary's capabilities. Alternatively, extend the provided MediaModel class. ```php namespace App\Models; use AchyutN\LaravelHelpers\Traits\HasTheMedia; use Spatie\MediaLibrary\HasMedia; class Post extends Model implements HasMedia { use HasTheMedia; } ``` ```php namespace App\Models; use AchyutN\LaravelHelpers\Models\MediaModel; class Post extends MediaModel { // } ``` -------------------------------- ### MediaModel Abstract Base Class Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Extend this abstract model to automatically include the HasTheMedia trait and HasMedia interface. Useful for models that require media support. ```php cover(), $article->small_cover(), etc. // Optionally override collections: protected array $theMediaCollections = ['cover', 'thumbnail']; } $article = Article::find(5); $article->addMedia(request()->file('image'))->toMediaCollection('cover'); return response()->json(['cover_url' => $article->cover()]); ``` -------------------------------- ### Select English or Nepali String by Locale Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Returns either the English or Nepali version of a string based on the current locale. Falls back to the non-empty value if the preferred locale's value is blank. Useful for displaying bilingual content. ```php getLocale(); // 'np' or 'en' return [ 'city_name' => english_nepali($cityNepali, $cityEnglish, $locale), 'province' => english_nepali($provinceNepali, $provinceEnglish, $locale), ]; ``` -------------------------------- ### ApiBaseController Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Provides standardized JSON response helpers for API controllers. ```APIDOC ## ApiBaseController ### Description Extends Laravel's base controller and provides three methods for consistent JSON response formatting. Extend this instead of `Controller` for API controllers. ### Methods - `api_success($data, $message)`: Returns a successful JSON response. - `api_error($exception)`: Returns a JSON response for exceptions, logging the error. - `custom_error($status, $message)`: Returns a custom JSON error response. ### Usage Example ```php namespace App\Http\Controllers\Api; use AchyutN\LaravelHelpers\Controller\ApiBaseController; use App\Models\Post; class PostController extends ApiBaseController { public function index() { try { $posts = Post::paginate(15); return $this->api_success($posts, 'Posts retrieved successfully.'); // Response: { "status": 200, "data": { ... }, "message": "Posts retrieved successfully." } } catch (\Exception $e) { return $this->api_error($e); // Logs the exception via Log::error() // Response: { "status": , "data": [], "message": "" } } } public function store(Request $request) { if (!auth()->check()) { return $this->custom_error(401, 'Unauthenticated.'); // Response: { "status": 401, "data": [], "message": "Unauthenticated." } } $post = Post::create($request->validated()); return $this->api_success($post, 'Post created.'); } } ``` ``` -------------------------------- ### Use HasTheDashboardTraits for Combined Functionality Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Employ the HasTheDashboardTraits trait to include both HasTheSlug and HasTheMedia functionalities in your model. ```php body); // pre-strip HTML before word count } } $article = Article::find(1); // Assume $article->body has ~450 words echo $article->minutes_read; // 3 echo $article->minutes_read_text; // "3 mins read" $short = Article::find(2); // ~80 words echo $short->minutes_read; // 1 (minimum enforced) echo $short->minutes_read_text; // "1 min read" // Use in API responses: return response()->json([ 'title' => $article->title, 'read_time' => $article->minutes_read_text, ]); ``` -------------------------------- ### CustomPaginator Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Provides a slim pagination response format, replacing Laravel's default. ```APIDOC ## CustomPaginator ### Description Replaces Laravel's default `LengthAwarePaginator` serialization. Registered automatically via `LaravelHelperProvider` as an alias, so all `->paginate()` calls in the application produce this format without any code changes. ### Usage No code changes are needed after package installation. Any `paginate()` call will automatically return the custom format. ```php // Any paginate() call returns the custom format: $posts = Post::paginate(10); return response()->json($posts); ``` ### Response Shape ```json { "data": [ { "id": 1, "title": "..." }, ... ], "total": 42, "perPage": 10, "page": 1 } ``` ### Comparison to Laravel Default Laravel's default includes: `first_page_url`, `last_page_url`, `next_page_url`, `prev_page_url`, `links`, `from`, `to`, `last_page`, `path`, etc. ``` -------------------------------- ### CanBeApproved: Timestamp-Based Approval Workflow Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Adds `approved_at` and `rejected_at` timestamps to manage model approval states. Automatically applies `ApprovedScope` to filter queries. Column names can be customized. ```php timestamp('approved_time')->nullable(); // $table->timestamp('rejected_time')->nullable(); $comment = Comment::withAll()->find(1); // withAll() bypasses the global scope // State transitions: $comment->setApproved(); // approved_time = now(), rejected_time = null -> true $comment->setRejected(); // rejected_time = now(), approved_time = null -> true $comment->setPending(); // both columns = null -> true // Query scopes: Comment::get(); // Only approved (global scope) Comment::withPending()->get(); // Approved + pending (not rejected) Comment::onlyPending()->get(); // Neither approved nor rejected Comment::withoutApproved()->get(); // Pending + rejected Comment::withRejected()->get(); // Only rejected (rejected_at set, approved_at null) Comment::onlyRejected()->get(); // All with rejected_at set (regardless of approved_at) Comment::withAll()->count(); // All records, no scope applied ``` -------------------------------- ### HasTheDashboardTraits: Combine Slug and Media Management Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Use this trait for content models requiring both automatic slug generation and media management. It composes HasTheSlug and HasTheMedia traits. ```php 'My First Post']); echo $post->slug; // "my-first-post" echo $post->cover(); // null (no media yet) ``` -------------------------------- ### Implement Approval Logic with CanBeApproved Trait Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Add approval and rejection capabilities to your models using the CanBeApproved trait. Ensure your table has 'approved_at' and 'rejected_at' timestamp columns. ```php use AchyutN\LaravelHelpers\Traits\CanBeApproved; class Post extends Model { use CanBeApproved; } ``` ```php $post->setApproved(); $post->setRejected(); $post->setPending(); ``` -------------------------------- ### Standardized API Responses with ApiBaseController Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Extend ApiBaseController for API controllers to provide consistent JSON responses. It includes helpers for success and error messages, logging exceptions automatically. ```php api_success($posts, 'Posts retrieved successfully.'); // Response: { "status": 200, "data": { ... }, "message": "Posts retrieved successfully." } } catch (\Exception $e) { return $this->api_error($e); // Logs the exception via Log::error() // Response: { "status": , "data": [], "message": "" } } } public function store(Request $request) { if (!auth()->check()) { return $this->custom_error(401, 'Unauthenticated.'); // Response: { "status": 401, "data": [], "message": "Unauthenticated." } } $post = Post::create($request->validated()); return $this->api_success($post, 'Post created.'); } } ``` -------------------------------- ### Manage Model Activity with CanBeInactive Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Use setInactive() to mark a model as inactive and setActive() to mark it as active. ```php $article->setInactive(); $article->setActive(); ``` -------------------------------- ### Use CanBeApproved Trait Scopes Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Use these query macros to filter records based on approval status. The default scope includes only approved records. ```php Post::withPending()->get(); Post::onlyPending()->get(); Post::withoutApproved()->get(); Post::withRejected()->get(); Post::onlyRejected()->get(); Post::withAll()->count(); ``` -------------------------------- ### Verify Current Password with MatchOldPassword Rule Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Use MatchOldPassword to confirm that a submitted password matches the authenticated user's current hashed password. This rule is intended for password change forms. ```php validate([ 'old_password' => ['required', new MatchOldPassword()], 'new_password' => ['required', 'min:8', 'confirmed'], 'new_password_confirmation' => ['required'], ]); auth()->user()->update([ 'password' => bcrypt($request->new_password), ]); // Error message on mismatch: "The old password does not match." ``` -------------------------------- ### MatchOldPassword Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Verifies that a submitted value matches the authenticated user's current hashed password. ```APIDOC ## MatchOldPassword ### Description Verifies that a submitted value matches the authenticated user's current hashed password using `Hash::check`. Intended for password-change flows. ### Usage ```php use AchyutN\LaravelHelpers\Rules\MatchOldPassword; // In a controller handling password change: $request->validate([ 'old_password' => ['required', new MatchOldPassword()], 'new_password' => ['required', 'min:8', 'confirmed'], 'new_password_confirmation' => ['required'], ]); auth()->user()->update([ 'password' => bcrypt($request->new_password), ]); ``` ### Error Message - `The old password does not match.` ``` -------------------------------- ### Select Locale-Based Values Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Use the english_nepali function to select a value based on the provided locale ('en' for English, 'ne' for Nepali). ```php timestamp('disabled_at')->nullable(); $product = Product::withInactive()->find(1); // include inactive to retrieve it // Toggle state: $product->setInactive(); // disabled_at = now() -> true $product->setActive(); // disabled_at = null -> true // Query scopes: Product::get(); // Only active products (global scope) Product::withInactive()->get(); // Active + inactive products Product::onlyInactive()->get(); // Only inactive products Product::withoutInactive()->count(); // Active only (explicit, same as default) ``` -------------------------------- ### Convert Numbers Between English and Nepali Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Use the english_nepali_number function to convert numbers between English and Nepali numeral systems. ```php validate([ 'latitude' => [new LatitudeRule()], ]); ``` -------------------------------- ### Use HasTheSlug Trait for Model Slugs Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Integrate the HasTheSlug trait into your model to automatically generate slugs. Ensure your model has a 'slug' column and optionally define the source column via $sluggableColumn. ```php getLocale()); // Converts based on active locale ``` ``` -------------------------------- ### Validate Longitude Input Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Use the LongitudeRule to ensure that the 'longitude' input is a numeric value within the valid range of -180 to 180. ```php use AchyutN\LaravelHelpers\Rules\LongitudeRule; $request->validate([ 'longitude' => [new LongitudeRule()], ]); ``` -------------------------------- ### Override CanBeApproved Column Names Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Define constants in your model to use custom column names for approval timestamps. ```php class Post extends Model { use CanBeApproved; public const APPROVED_AT = 'approved_time'; public const REJECTED_AT = 'rejected_time'; } ``` -------------------------------- ### Use CanBeInactive Trait Scopes Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Override the default scope (which includes only active models) using these query macros. ```php Article::withInactive()->get(); Article::onlyInactive()->get(); Article::withoutInactive()->count(); ``` -------------------------------- ### Convert Numbers Between English and Nepali Scripts Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt The `english_nepali_number()` function converts digits between English (0-9) and Nepali (०-९) scripts. It preserves non-digit characters like spaces and commas. ```php getLocale()); // Converts based on active locale ``` -------------------------------- ### Use CanBeInactive Trait Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Include the CanBeInactive trait in your Eloquent model to manage active/inactive states. ```php use AchyutN\LaravelHelpers\Traits\CanBeInactive; class Article extends Model { use CanBeInactive; } ``` -------------------------------- ### LongitudeRule Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Ensures a field is numeric and within the valid WGS-84 longitude range of −180 to 180. ```APIDOC ## LongitudeRule ### Description Ensures a field is numeric and within the valid WGS-84 longitude range of −180 to 180. ### Usage ```php use AchyutN\LaravelHelpers\Rules\LongitudeRule; $validated = $request->validate([ 'longitude' => ['required', new LongitudeRule()], ]); ``` ### Passing Values `85.3240`, `-180`, `0`, `180` ### Failing Values `181`, `-181`, `"not-a-number"` ### Error Messages - `The longitude must be a number.` - `The longitude must be between -180 and 180.` ``` -------------------------------- ### HasTheSlug Trait for Eloquent Models Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Use the HasTheSlug trait to automatically generate URL slugs from a model attribute. Requires a 'slug' column in your database table. The route key is automatically set to 'slug'. ```php 'Hello World!']); echo $post->slug; // "hello-world" // Route model binding resolves by slug: // Route::get('/posts/{post}', [PostController::class, 'show']); // GET /posts/hello-world -> Post::where('slug', 'hello-world')->firstOrFail() ``` -------------------------------- ### LatitudeRule Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Ensures a field is numeric and within the valid WGS-84 latitude range of −90 to 90. ```APIDOC ## LatitudeRule ### Description Ensures a field is numeric and within the valid WGS-84 latitude range of −90 to 90. ### Usage ```php use AchyutN\LaravelHelpers\Rules\LatitudeRule; // In a Form Request or controller: $validated = $request->validate([ 'lat' => ['required', new LatitudeRule()], ]); ``` ### Passing Values `27.7172`, `-90`, `0`, `90` ### Failing Values `91`, `-91.5`, `"abc"` ### Error Messages - `The lat must be a number.` - `The lat must be between -90 and 90.` ``` -------------------------------- ### Override CanBeInactive Column Name Source: https://github.com/achyutkneupane/laravel-helpers/blob/master/README.md Define a constant in your model to specify a custom column name for the inactive timestamp. ```php class Article extends Model { use CanBeInactive; public const INACTIVE_AT = 'disabled_at'; } ``` -------------------------------- ### Validate Geographic Longitude with LongitudeRule Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Employ LongitudeRule to validate that a field is numeric and falls within the WGS-84 longitude range of -180 to 180. This is useful in validation scenarios. ```php validate([ 'longitude' => ['required', new LongitudeRule()], ]); // Passing values: 85.3240, -180, 0, 180 // Failing values: 181, -181, "not-a-number" // Error messages: // "The longitude must be a number." // "The longitude must be between -180 and 180." ``` -------------------------------- ### Validate Geographic Latitude with LatitudeRule Source: https://context7.com/achyutkneupane/laravel-helpers/llms.txt Use LatitudeRule to ensure a field contains a numeric value within the valid WGS-84 latitude range of -90 to 90. It's suitable for form requests or controllers. ```php validate([ 'lat' => ['required', new LatitudeRule()], 'lng' => ['required', new LongitudeRule()], ]); // Passing values: 27.7172, -90, 0, 90 // Failing values: 91, -91.5, "abc" // Error messages: // "The lat must be a number." // "The lat must be between -90 and 90." ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.