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

Surveybundle Laravel Package

xlabs/surveybundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require xlabs/surveybundle
    

    Add to config/app.php under providers:

    Xlabs\SurveyBundle\SurveyBundle::class,
    

    Publish the bundle’s assets and config:

    php artisan vendor:publish --provider="Xlabs\SurveyBundle\SurveyBundle" --tag=config
    php artisan vendor:publish --provider="Xlabs\SurveyBundle\SurveyBundle" --tag=assets
    
  2. First Use Case: Creating a Survey

    • Define a survey in config/survey.php or via migrations:
      // Example: config/survey.php
      'surveys' => [
          'customer_satisfaction' => [
              'title' => 'Customer Satisfaction',
              'questions' => [
                  ['type' => 'text', 'question' => 'How was your experience?'],
                  ['type' => 'rating', 'question' => 'Rate our service (1-5)', 'min' => 1, 'max' => 5],
              ],
          ],
      ],
      
    • Load surveys in a controller:
      use Xlabs\SurveyBundle\SurveyManager;
      
      public function showSurvey(SurveyManager $manager)
      {
          $survey = $manager->getSurvey('customer_satisfaction');
          return view('surveys.show', compact('survey'));
      }
      
  3. Basic Routing Configure routes in routes/web.php:

    use Xlabs\SurveyBundle\Http\Controllers\SurveyController;
    
    Route::prefix('surveys')->group(function () {
        Route::get('/{slug}', [SurveyController::class, 'show']);
        Route::post('/{slug}/submit', [SurveyController::class, 'submit']);
    });
    

Implementation Patterns

1. Dynamic Survey Loading

  • Use Case: Load surveys dynamically (e.g., per user segment).
    // In a controller or service
    $surveyManager = app(SurveyManager::class);
    $survey = $surveyManager->getSurvey('dynamic_survey', ['user_id' => auth()->id()]);
    
    • Override getSurvey() in a custom service to fetch from a database or API.

2. Question Types and Validation

  • Supported Types: text, rating, multiple_choice, checkbox, date.
  • Validation: Leverage Laravel’s validation rules via SurveyBundle's Question class:
    // Example: Add validation to a question
    $question = new Question([
        'type' => 'text',
        'question' => 'What did you like?',
        'rules' => 'required|min:10',
    ]);
    
  • Custom Questions: Extend Xlabs\SurveyBundle\Question\Question and register in config/survey.php:
    'custom_question_types' => [
        'custom_type' => \App\CustomQuestion::class,
    ],
    

3. Survey Responses

  • Storing Responses: Use the SurveyResponse model (auto-generated by the bundle) or extend it:
    // Example: Submit a response
    $response = $surveyManager->submitResponse('customer_satisfaction', [
        'answers' => [
            'q1' => 'Great experience!',
            'q2' => 4,
        ],
        'metadata' => ['user_id' => auth()->id()],
    ]);
    
  • Querying Responses:
    $responses = SurveyResponse::where('survey_slug', 'customer_satisfaction')->get();
    

4. Integration with Forms

  • Blade Templates: Use the bundle’s views (resources/views/vendor/survey/) or override them:
    @extends('surveys.layout')
    @section('content')
        @include('survey::form', ['survey' => $survey])
    @endsection
    
  • Dynamic Form Generation:
    // In a controller
    return view('surveys.custom_form', [
        'questions' => $survey->getQuestions()->map(fn($q) => $q->toArray()),
    ]);
    

5. Survey Analytics

  • Basic Analytics: Use Eloquent to aggregate responses:
    $avgRating = SurveyResponse::where('survey_slug', 'customer_satisfaction')
        ->avg('answers->q2'); // Assuming 'q2' is the rating question
    
  • Custom Analytics: Extend the SurveyResponse model or create a service to process raw data.

6. Localization

  • Translate Surveys: Override question text in language files:
    // resources/lang/en/survey.php
    return [
        'customer_satisfaction' => [
            'title' => 'Customer Satisfaction (EN)',
            'questions' => [
                'q1' => 'How was your experience? (EN)',
            ],
        ],
    ];
    
  • Fallback: The bundle defaults to config/survey.php if translations are missing.

Gotchas and Tips

1. Configuration Quirks

  • Missing Surveys: If a survey slug isn’t found, check:
    • config/survey.php for typos in the surveys array.
    • Database migrations (if using dynamic surveys).
    • Cached config: Run php artisan config:clear if changes aren’t reflected.
  • Question Types: Unsupported types will throw InvalidQuestionTypeException. Ensure all question types are registered in config/survey.php under custom_question_types.

2. Debugging

  • Response Validation: If submissions fail silently, enable debug mode and check Laravel’s validation logs:
    // In a controller
    $validator = Validator::make($request->all(), $survey->getValidationRules());
    if ($validator->fails()) {
        \Log::error('Survey validation failed:', $validator->errors());
    }
    
  • Database Issues: Ensure the survey_responses table exists (run migrations if needed).

3. Performance Tips

  • Eager Load Surveys: Cache survey configurations in a service:
    // In a service class
    private $surveys = [];
    
    public function getSurvey(string $slug): Survey
    {
        if (!isset($this->surveys[$slug])) {
            $this->surveys[$slug] = $surveyManager->getSurvey($slug);
        }
        return $this->surveys[$slug];
    }
    
  • Batch Responses: Use chunking for large response datasets:
    SurveyResponse::where('survey_slug', 'customer_satisfaction')->chunk(100, function ($responses) {
        // Process chunk
    });
    

4. Extension Points

  • Custom Survey Storage: Override SurveyManager to fetch surveys from an API or NoSQL:
    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(SurveyManager::class, function ($app) {
            return new \App\Services\CustomSurveyManager();
        });
    }
    
  • Event Listeners: Extend survey logic via events (e.g., SurveySubmitted):
    // In EventServiceProvider
    protected $listen = [
        \Xlabs\SurveyBundle\Events\SurveySubmitted::class => [
            \App\Listeners\LogSurveyResponse::class,
        ],
    ];
    

5. Common Pitfalls

  • CSRF on Submissions: Ensure survey submission routes include @csrf in Blade templates or middleware.
  • Slug Conflicts: Avoid duplicate survey slugs in config/survey.php.
  • File Uploads: If using file question types, configure storage in config/filesystems.php and validate uploads manually.

6. Testing

  • Unit Tests: Mock SurveyManager to test controllers:
    $this->mock(SurveyManager::class)->shouldReceive('getSurvey')
        ->once()->andReturn($mockSurvey);
    
  • Feature Tests: Use actingAs() for authenticated survey submissions:
    $response = $this->actingAs($user)->post('/surveys/customer_satisfaction/submit', [
        'answers' => ['q1' => 'Test'],
    ]);
    $response->assertRedirect('/thank-you');
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware