blaze-rowland
blaze-rowland

Reputation: 117

Creating a row in two tables with one form. How do I add IDs connecting them?

I'm using laravel 5.6 and I'm trying to insert a row into two different tables and link them together inside public function store()

Here's what I have:

public function store(Request $request)
    {
        $this->validate($request, [
          'name'         => 'required',
          'email'        => 'required',
          'project'      => 'required',
          'project_type' => 'required',
          'budget'       => 'required'
        ]);

        $client = new Client;
        $project = new Project;

        $client->name       = $request->input('name');
        $client->email      = $request->input('email');
        $client->save();

        $project->project      = $request->input('project');
        $project->project_type = $request->input('project_type');
        $project->budget       = $request->input('budget');
        $project->save();

        return redirect('/admin/clients');
    }

I need to do something like:

$client->project_id = $project->id;
$project->client_id = $client->id;

But that obviously won't work. How would I go about getting IDs for these rows whenever the rows haven't been created yet to access them? Is it possible? If not I'll find a work around or approach it a different way.

Thanks.

Upvotes: 0

Views: 48

Answers (1)

Erick Patrick
Erick Patrick

Reputation: 451

If you created your tables allowing project_id and client_id be null, then add the following snippet after saving the client and project:

$client->project_id = $project->id;
$client->save();
$project->client_id = $client->id;
$project->save();

But what I recommend you is to have one foreign key to the other table in Client or Project but not both.

Then you can define eloquent one to one (https://laravel.com/docs/5.5/eloquent-relationships#one-to-one) relationship to get the record of the other table.

Upvotes: 2

Related Questions