Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fluentd's avatar

Posting Data to multiple tables with a single form

I was hoping to get some ideas for posting data to multiple tables in mysql. For example. I want to have one form that can be filled out to include information for a family then information for children in a different table and then a contact table that is also different but still in relationship to the family. I then would like to be able to add data to the children which includes the classes that they are enrolled in.

0 likes
36 replies
bobbybouwmann's avatar
Level 88

If you have a relation between those tables then you can look at the documentation how to do it: http://laravel.com/docs/5.0/eloquent

If you don't have a relation between the models you can do something like this:

public function create() 
{
    $family = Family::create([
        Input::get('input1'),
        Input::get('input2')
    ];

    $child = Child::create([
        Input::get('input3'),
        Input::get('input4')
    ];

    $contact = Contact::create([
        Input::get('input5'),
        Input::get('input6')
    ];
}
3 likes
thepsion5's avatar

I haven't tested this, but I'm pretty sure you can use the Input facade to get an array of parameters. So, your form fields could look like this:

  • [family]name
  • [family]income
  • [family]preferred_elder_god

And use JS to create multiple children fields that would look like this:

  • [children][0][first]
  • [children][0][last]
  • [children][0][age]
  • [children][0][receptiveness_to_madness]

Then, you should be able to process the family data and multiple children like so:

$family = FamilyModel::create( Input::get('family') );

$childModels = [];
foreach( Input::get('children') as $childData) {
    $childModels[] = new ChildModel($childData);
}

$family->children()->saveMany($childModels);
1 like
Penderis's avatar

put the helper function create as @blackbird says in a repository so from controller you will call your validation helper if passed then you run your create method and pass it your validated and sanitized input.

 $createData->create($input);
return View::make('on.your.merry.way');
1 like
fluentd's avatar

Thanks, I did have the relationships in place I guess I was on the right track. I will review the Relationships video from the L5 Fundamentals.

fluentd's avatar

@blackbird So once I setup the relationship between the two models with hasmany and belongsto what would be the next step in collecting data from one form into the two tables? Sorry for my ignorance I am very new to all of this but have come a long way since I first learned about Laravel.

bobbybouwmann's avatar

Yea exactly! Give it a try and if you get any problems you know where to find us ;)

fluentd's avatar

@blackbird Sorry I was asking what I need to do next. I am not quite sure how to pull data into two separate tables from a single form.

bobbybouwmann's avatar

Like I showed before, for each model you perform the create statement with the correct values from your form

$family = Family::create([
        Input::get('input1'),
        Input::get('input2')
]);

$child = Child::create([
        Input::get('input3'),
        Input::get('input4')
]);
fluentd's avatar

Ok so right now my FamiliesController store method is collecting all the fields via

Family::create($request->all());

So do I need to break it down into individual fields now?

bobbybouwmann's avatar

Yea, because you don't need all the fields for the Family object. You can also do something like this:

$family = Family::create(Request::only('input1', 'input2', 'input3'));
$child = Child::create(Request::only('input4', 'input5', 'input6'));
1 like
jekinney's avatar

You can chain the relationships together, but the end result is the same.

$input = Input::all() //or request in L5
$first =  model::create($input); 
//this assumes your fillable fields are set correctly. As the un-needed data will just drop off and not used.
 $first->relationshipnametosecondmodel()->create($input);

This route also has the benefit of setting the relationship data too. Example: User model and Profiles. Generally your profile will have a user_id field, and chaining will fill the user_id with the proper user_id.

fluentd's avatar

That was going to be my second question. How do I go about filling in the family_id from the ID field of the families model.

Family::create($request->all());
$family = model::create($input);

$family->contacts()->create($input);
$family->memberships()->create($input);  // A third model of data to be filled in from the form.

From this I am still trying to understand how to fill the ID from families table into the family_id field for both contacts and memberships table. (not even sure if this is the proper way to do it but that is what I came up with to reference each other)

Here are the two relationships from the family model.

public function memberships()
{
    return $this->hasMany('App\Membership');
}

public function contacts()
{
    return $this->hasMany('App\Contact');
}
1 like
fluentd's avatar

I have tried about 10 or so different combinations and I am just not understanding the syntax of what I am suppose to do. Here is what I currently have. Is there anyone that could walk me through step by step as I am just not getting it.

$input = Family::all($request->all());
$family = Family::create($input);

$family->contacts()->create($input);
$family->memberships()->create($input);

$input['id'] = contacts::family_id();
jekinney's avatar

I don't understand why your querying the database for all family object and trying to create a new family from that query and not input from a form.

fluentd's avatar

So my FamiliesController store method looks like the following. I am still not able to get it to work but think I am on the right track.

public function store(FamilyRequest $request)
{

// My original method for getting all input data.   
// Family::create($request->all());

    $family = Family::create(Request::only(
        'family_name', 
        'marketing', 
        'health_insurance', 
        'health_insurance_policy', 
        'doctor_name', 
        'doctor_phone'
    ));
    $contact = Contact::create(Request::only( 
        'first_name',
        'middle_name',
        'last_name',
        'relationship',
        'contact_type',
        'address1',
        'address2',
        'city',
        'state',
        'zip',
        'cell_phone',
        'home_phone',
        'work_phone',
        'email',
        'is_primary'
    ));

    return redirect('families');
}
bobbybouwmann's avatar

So your controller is fine now. Are you sure you have migrated the database?

To be sure try this to see if you get the correct results, try this and check if you get the correct objects back ;)

$family = Family::create(Request::only(
    'family_name', 
    'marketing', 
    'health_insurance', 
    'health_insurance_policy', 
    'doctor_name', 
    'doctor_phone'
));

$contact = Contact::create(Request::only( 
    'first_name',
    'middle_name',
    'last_name',
    'relationship',
    'contact_type',
    'address1',
    'address2',
    'city',
    'state',
    'zip',
    'cell_phone',
    'home_phone',
    'work_phone',
    'email',
    'is_primary'
));

dd($family, $contact);

return redirect('families');
fluentd's avatar

I get the following.

FatalErrorException in FamiliesController.php line 46: Class 'App\Http\Controllers\Request' not found

Here are the use at the top of the FamiliesController

use App\Http\Requests;
use App\Http\Requests\FamilyRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use App\Family;

Line 46

$family = Family::create(Request::only( // Line 46
bobbybouwmann's avatar

You need to update Request here to $request, this is because you already have the Request object by method injection

$family = Family::create($request->only(
    'family_name', 
    'marketing', 
    'health_insurance', 
    'health_insurance_policy', 
    'doctor_name', 
    'doctor_phone'
));

I think you can figure the other one by yourself ;)

fluentd's avatar

Fixed both, now it looks like it can't find the Contact model.

FatalErrorException in FamiliesController.php line 55:
Class 'App\Http\Controllers\Contact' not found

Ok fixed that by adding:

use App\Contact;
fluentd's avatar

Now onto the next problem... :(

QueryException in Connection.php line 614: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (billing_dev.contacts, CONSTRAINT contacts_family_id_foreign FOREIGN KEY (family_id) REFERENCES families (id) ON DELETE CASCADE) (SQL: insert into contacts (first_name, last_name, updated_at, created_at) values (John, Doe, 2015-03-03 22:10:29, 2015-03-03 22:10:29))

fluentd's avatar

@blackbird I have still not been able to get this working yet, any chance I could get some advice on it? I am still now sure how to associate the family model with the contact model and have the family_id field filled in with the family's ID field.

bobbybouwmann's avatar

Here is an example of how you can do it!

class FamilyController extends Controller {

    public function store(Request $request)
    {
        $family = Family::create([
            'family_name' => $request->input('family_name'),
            'other_field' => $request->input('other_field'),
            'another_field' => $request->input('another_field'),
        ]);

        // Now you have a Family object so we can use that for the contact model

        $content = Contact::create([
            'family_id' => $family->id, // Notice the family ID here
            'other_field' => $request->input('other_field'),
            'another_field' => $request->input('another_field'),
        ]);

        // Redirect or whatever you want to do here
    }

    // Other methods

}
1 like
fluentd's avatar

I will test this out. I did notice my relationship is setup for the family_id field in the contacts table. I Manually added a contact using phpmyadmin and the family_id field was a drop down with only available family ID's to choose from. So with that being said I think once I use this suggestion I might be set. I will report back thanks @blackbird

I also wanted to note that going through the Eloquent ORM documentation has helped a lot too.

fluentd's avatar

Looks like I am getting some where I can see the SQL query working but it doesnt like empty fields. How do I make it so that the fields can be empty. In the family table it doesn't throw any errors like this, why is it doing it for the Contacts table?

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'address1' cannot be null (SQL: insert into contacts (family_id, first_name, middle_name, last_name, relationship, address1, address2, city, state, zip, cell_phone, home_phone, work_phone, email, is_primary, updated_at, created_at) values (1, First Name, A, Last Name, 2, , , , , , , , , , , 2015-03-11 21:18:14, 2015-03-11 21:18:14))

I guess I can just add ->nullable() to my migrations table? Would this be correct? Only problem is I don't understand why it doesnt error on me with the family table for fields that I leave blank and they are not nullable fields.

fluentd's avatar

Looks like I got everything fixed. So my problem was that if that field was not on the form I was submitting it needed to be nullable. After I added all the fields to the form everything worked fine. Thanks @blackbird for all your help, I really appreciate it!

fluentd's avatar

Hey @blackbird Now I would like to pull both Family information and Contact information onto a view. In my index method of my FamiliesController I am trying to use Querying Relations, so I came up with.

$contacts = Family::find(1)->contacts()->where('is_primary', '=', '1')->get();

Which seems to give me only the contact that is set to primary, which is what I want. Now my question is how do I access that data in the view? I currently have a foreach setup in a table like this: (I already passed the variable $contacts to the view in the controller)

@foreach ($families as $family)
            <tr>
                <td>{{ $family->id }}</td>
                <td>{{ $family->created_at->toFormattedDateString() }}</td>
                <td>{{ $family->contacts->first_name }}</td>
                <td>{{ $family->contacts->last_name }}</td>
                <td><a class="btn btn-blue btn-xs" roll="button" href="{{ url('/families', $family->id) }}">{{ $family->family_name }}</a></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                    <a class="btn btn-green btn-xs btn-icon icon-left visible-xs-block" roll="button" href="{{ url('/families', $family->id) }}">View<i class="entypo-user"></i></a>
                    <a class="btn btn-default btn-xs btn-icon icon-left visible-xs-block" roll="button" href="{!! url('/families/' . $family->id . '/edit') !!}">Edit<i class="entypo-cog"></i></a>
                </td>
            </tr>
        @endforeach

as you can see I am trying to chain $family->contacts->last_name to access the contacts last_name but I think I am having a problem because I am returning a collection?

Next

Please or to participate in this conversation.