How to insert data into different tables using the same controller?

I am using Laravel (coming from CodeIgniter) and I am struggling to get a table containing a populated foreign key.

I have two tables: PeopleandFriends

My table Peoplehas fields like "First Name", "Last Name", etc.

At the bottom of my form, I can add a friend. Each friend can have a "First Name", "Last Name", etc. I can add as many friends as I want.

I successfully populate the table Peopleand then scroll through my friends fields to populate the table Friends.

Mycontroller.php

if ($person->save()) {  // Save the primary record.

    // check if there are any friends to save.
    $friendsArray = array_filter($input['friend']);

    if (empty($friendsArray)) {
        // No friends to insert.
    } else {
        $friend = new Friend();

        $friend->person_id = $person->id;
        $friend->friend_data = json_encode(array('friend' => $input['friend']));

        $friend->save();
    }
}

If I exit $ friend, I see everything correctly. For example,

[attributes:protected] => Array
    (
        [person_id] => 4
        [friend_data] => {"friend":{"firstName":"Tyler","lastName":"Durden","address":"12345 Street","city":"My City","state":"CA","zip":"12345"}}
    )

Friend. , , .

Friends.

...
Schema::create('friends', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('person_id')->unsigned();
    $table->foreign('person_id')->references('id')->on('people');
    $table->text('friend_data');
    $table->timestamps();
});

2

:

Base table or view not found: 1146 Table 'myapplication.friend' doesn't exist

, , . Friend, Friends.

3

:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Friend extends Model
{
    //
}
+4
1

Laravel . , . Friend. , :

protected $table = 'friends';

, , .

+2

Source: https://habr.com/ru/post/1623817/


All Articles