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

Laravel Larakit Form Laravel Package

larakit/laravel-larakit-form

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require larakit/laravel-larakit-form
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Larakit\LarakitForm\LarakitFormServiceProvider"
    
  2. Basic Form Setup Create a form class extending Larakit\LarakitForm\Form:

    namespace App\Forms;
    
    use Larakit\LarakitForm\Form;
    
    class ContactForm extends Form
    {
        public function rules()
        {
            return [
                'name' => 'required|string|max:255',
                'email' => 'required|email',
                'message' => 'required|string',
            ];
        }
    }
    
  3. Render the Form in a Blade View

    use App\Forms\ContactForm;
    
    // In your controller
    $form = new ContactForm();
    return view('contact', ['form' => $form]);
    
    {!! $form->render() !!}
    
  4. Handle Form Submission

    public function store(Request $request)
    {
        $form = new ContactForm($request->all());
        if ($form->passes()) {
            // Process valid data
            $form->save(); // If using persistence
        }
        return back()->withErrors($form->errors());
    }
    

Where to Look First

  • Documentation: Check the GitHub README for quick-start guides.
  • Form Class Structure: Study app/Forms/ for examples of form validation rules and custom logic.
  • Blade Directives: Explore @form and @endform directives for dynamic form rendering.
  • Config File: Review config/larakit-form.php for global settings like default validation messages or error handling.

Implementation Patterns

Common Workflows

  1. Dynamic Form Rendering Use Blade directives to render forms dynamically:

    @form('App\Forms\ContactForm', ['method' => 'POST', 'class' => 'my-form'])
        @text('name', null, ['placeholder' => 'Your Name'])
        @textarea('message')
        @submit('Send Message')
    @endform
    
  2. Reusable Form Components Create modular form classes for common use cases (e.g., LoginForm, UserProfileForm). Extend base forms to inherit rules and logic:

    class UserProfileForm extends ContactForm
    {
        public function rules()
        {
            return parent::rules() + [
                'avatar' => 'image|mimes:jpeg,png,jpg|max:2048',
            ];
        }
    }
    
  3. Form Persistence Use the save() method to persist form data to a model:

    $form = new UserProfileForm($request->all());
    if ($form->passes()) {
        $user = $form->save(new User()); // Attaches to a new User model
        // OR update existing model
        $user = $form->save($existingUser);
    }
    
  4. Custom Validation Logic Override the validate() method or use callbacks:

    public function validate()
    {
        $this->addRule('password', 'required|confirmed', 'Password confirmation failed.');
        $this->addRule('terms', 'accepted', 'You must accept the terms.');
    }
    
  5. Integration with Laravel Features

    • Localization: Use Laravel's localization for validation messages:
      public function messages()
      {
          return [
              'name.required' => 'The name field is required.',
          ];
      }
      
    • Authorization: Combine with Laravel Policies or Gates:
      public function authorize()
      {
          return Auth::user()->can('update-profile');
      }
      
  6. API Forms Disable CSRF and render as JSON:

    $form = new ContactForm($request->all());
    if ($form->fails()) {
        return response()->json($form->errors(), 422);
    }
    

Integration Tips

  • Larakit UI: Pair with Larakit UI for consistent styling.
  • Larakit Notifications: Use Larakit\Notification to send alerts after form submission.
  • Larakit Media: Integrate with Larakit\Media for file uploads in forms.
  • Testing: Use Laravel's testing tools to validate form submissions:
    $response = $this->post('/contact', [
        'name' => 'Test User',
        'email' => 'test@example.com',
        'message' => 'Hello!',
    ]);
    $response->assertSessionHasNoErrors();
    

Gotchas and Tips

Pitfalls

  1. CSRF Token Mismatch

    • Issue: Forms submitted via AJAX or without CSRF tokens may fail.
    • Fix: Ensure @csrf is included in Blade forms or disable CSRF for API routes:
      $form->csrf = false; // Disable CSRF for API forms
      
  2. Validation Rule Conflicts

    • Issue: Custom rules may override Laravel's built-in rules.
    • Fix: Use addRule() instead of rules() for dynamic rules:
      $this->addRule('custom_field', 'required|custom_rule', 'Custom error message.');
      
  3. Model Binding Issues

    • Issue: save() may not bind correctly to existing models.
    • Fix: Explicitly set the model or use fill():
      $user = $form->save($existingUser); // Ensure $existingUser is bound
      
  4. Form Caching

    • Issue: Cached forms may not reflect rule changes.
    • Fix: Clear config cache after updating rules:
      php artisan config:clear
      
  5. HTML_QuickForm2 Dependencies

    • Issue: Underlying HTML_QuickForm2 may cause conflicts with other packages.
    • Fix: Isolate form classes in a separate namespace or use composer autoload optimizations.

Debugging Tips

  • Enable Debug Mode Set debug to true in config/larakit-form.php to log validation errors and form events.

  • Dump Form Data Use dd($form->getData()) or dd($form->getErrors()) to inspect form state.

  • Check Events Listen for form events to debug submission:

    $form->on('beforeValidate', function() {
        \Log::debug('Form data before validation:', $this->getData());
    });
    

Extension Points

  1. Custom Renderers Override the render() method to use a different templating engine (e.g., Vue.js):

    public function render()
    {
        return view('custom.form', ['form' => $this]);
    }
    
  2. Dynamic Rule Loading Load rules from a database or external service:

    public function rules()
    {
        $dynamicRules = RuleRepository::getRules('contact_form');
        return array_merge($this->defaultRules(), $dynamicRules);
    }
    
  3. Form Events Extend functionality with events:

    $form->on('afterValidate', function() {
        // Post-validation logic
    });
    
  4. Custom Field Types Create custom field classes by extending Larakit\LarakitForm\Field:

    class CustomSelectField extends Field
    {
        public function render()
        {
            // Custom rendering logic
        }
    }
    
  5. Form Groups Organize forms into groups for multi-step workflows:

    class MultiStepForm extends Form
    {
        public function groups()
        {
            return [
                'personal' => ['name', 'email'],
                'address' => ['street', 'city'],
            ];
        }
    }
    
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