Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Reference Gender Laravel Package

baks-dev/reference-gender

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require baks-dev/reference-gender
    

    Ensure your project uses PHP 8.4+ (check composer.json and php -v).

  2. First Use Case Import the core class and use the static methods to fetch gender-related data:

    use BaksDev\ReferenceGender\Gender;
    
    // Get all genders
    $allGenders = Gender::all();
    
    // Get a specific gender by ID
    $maleGender = Gender::find(1);
    
    // Check if a gender exists
    $exists = Gender::exists(2);
    
  3. Where to Look First

    • Gender class: Core functionality (methods like all(), find(), exists()).
    • config/reference-gender.php: Default configurations (e.g., language, data sources).
    • src/Exceptions/: Custom exceptions for error handling.

Implementation Patterns

Usage Patterns

  1. Data Retrieval

    • Fetch all genders (e.g., for dropdowns):
      $genders = Gender::all()->pluck('name', 'id');
      
    • Filter by language:
      $ruGenders = Gender::all('ru'); // Assuming 'ru' is a supported locale
      
  2. Integration with Eloquent Models Add a gender relationship to a model (e.g., User):

    use BaksDev\ReferenceGender\Traits\HasGender;
    
    class User extends Model
    {
        use HasGender;
    
        // Automatically adds `gender_id` to fillable and casts it to integer.
    }
    
  3. Validation Use the package’s rules for form validation:

    use BaksDev\ReferenceGender\Rules\GenderExists;
    
    $request->validate([
        'gender_id' => ['required', new GenderExists],
    ]);
    
  4. Localization Override default translations by publishing the config:

    php artisan vendor:publish --provider="BaksDev\ReferenceGender\GenderServiceProvider" --tag="config"
    

    Then update config/reference-gender.php to specify locales (e.g., ['default' => 'en']).


Workflows

  1. Dynamic Gender Selection Use middleware to set a default gender for authenticated users:

    public function handle(Request $request, Closure $next)
    {
        if ($request->user()) {
            $request->user()->setDefaultGender(1); // ID for 'Male'
        }
        return $next($request);
    }
    
  2. API Responses Return gender data in API responses:

    return response()->json([
        'user' => [
            'name' => $user->name,
            'gender' => Gender::find($user->gender_id)?->name,
        ],
    ]);
    
  3. Seeding Seed gender data during project setup:

    use BaksDev\ReferenceGender\Database\Seeders\GenderSeeder;
    
    class DatabaseSeeder extends Seeder
    {
        public function run()
        {
            $this->call(GenderSeeder::class);
        }
    }
    

Integration Tips

  • Laravel Mix/Blade: Cache gender data in Blade directives for performance:
    @php
        $genders = \BaksDev\ReferenceGender\Gender::all()->keyBy('id');
    @endphp
    
  • Testing: Mock gender data in unit tests:
    $this->partialMock(Gender::class, function ($mock) {
        $mock->shouldReceive('find')->andReturn((object) ['id' => 1, 'name' => 'Male']);
    });
    
  • Custom Data Sources: Extend the package by implementing GenderRepositoryInterface for custom backends (e.g., database, API).

Gotchas and Tips

Pitfalls

  1. Locale Mismatches

    • If translations are missing for a locale, the package defaults to English. Ensure your config/reference-gender.php specifies supported locales:
      'locales' => ['en', 'ru'], // Add your locales here
      
  2. Database Seeder Conflicts

    • Running the GenderSeeder multiple times may cause duplicate entries. Check for existing data before seeding:
      if (!Gender::all()->isEmpty()) {
          return;
      }
      
  3. PHP Version Compatibility

    • The package requires PHP 8.4+. Using older versions will trigger runtime errors. Verify with:
      php -r "echo PHP_VERSION_ID >= 80400 || 'Upgrade PHP!';"
      
  4. Caching Issues

    • If gender data changes infrequently, cache the results to avoid repeated database/API calls:
      $genders = Cache::remember('genders', now()->addHours(1), function () {
          return Gender::all();
      });
      

Debugging

  1. Missing Gender Data

    • Check if the GenderSeeder ran or if data exists in your database table (gender by default). Run:
      php artisan db:seed --class=GenderSeeder
      
  2. Translation Errors

    • Verify translations exist in resources/lang/{locale}/gender.php or publish the package’s translations:
      php artisan vendor:publish --tag=reference-gender-translations
      
  3. Method Not Found

    • Ensure you’re using the fully qualified class name (BaksDev\ReferenceGender\Gender) or add a use statement at the top of your file.

Tips

  1. Extend Functionality

    • Add custom methods to the Gender class by creating a decorator:
      namespace App\Services;
      
      use BaksDev\ReferenceGender\Gender as BaseGender;
      
      class Gender extends BaseGender
      {
          public static function getActiveGenders()
          {
              return static::all()->where('active', true);
          }
      }
      
    • Override the binding in AppServiceProvider:
      $this->app->bind(Gender::class, function ($app) {
          return new App\Services\Gender();
      });
      
  2. Performance Optimization

    • Eager-load gender relationships in Eloquent queries:
      User::with('gender')->get();
      
  3. Testing

    • Use the Gender facade for cleaner tests:
      use BaksDev\ReferenceGender\Facades\Gender;
      
      public function testGenderExists()
      {
          $this->assertTrue(Gender::exists(1));
      }
      
  4. Custom Exceptions

    • Handle gender-related exceptions gracefully:
      try {
          $gender = Gender::find(999); // Non-existent ID
      } catch (\BaksDev\ReferenceGender\Exceptions\GenderNotFound $e) {
          abort(404, 'Gender not found');
      }
      
  5. Configuration Overrides

    • Override default table names in config/reference-gender.php:
      'table' => 'custom_gender_table',
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui