Laravel – how should I store data when I have form with many fields

Im wondering how should I store data when my form got too many fields, In my case I have 33 inputs and I had to create 4 models and migrations for different type of data (for example: basic user info, images, more user details and other details) and now I want to create store method but there is one problem my controller will be so long, I thought about using events but Im not sure if thats correct approach I would love every advice thank you in advance.

Answer

You can create a repository with a spearate methods that will store different parts of user data, and in case all of 33 fields are in user table, you could do it like this:

DB::beginTransaction();

try {
    $userId = $this->userRepository->store($request);
    $this->userRepository->storeImages($request, $userId);
    $this->userRepository->storeOtherDetails($request, $userId);

    DB::commit();
    // all good
} catch (Exception $e) {
    DB::rollback();
}

I’ve wrapped all of this in transaction, so in case on thing fails, the others won’t get stored.

storeImage and storeOtherDetails would then find the user and actually update those fields, so you could name those methods as updateUserImage or setUserImage.

If you have separate table for user images, with the matching model, you could create UserImageRepository and follow the same pattern.

Other option would be to create a static store method in the model, like so:

public static function createFromRequest($request)
    {
        self::create([])
    }

but then the model itself would be messy.