Why do not relations work for me in Laravel 5.4.2?

3

Hello friends, my problem is the following, for some days now I have been planning the relations of the game that I am doing with PHP using Laravel 5.4 and the following problem arises when creating users: I have two Tables: users and characters , a user can have many characters but one character only one User (one to many) in the table characters I have a column called > user_id which is related to the id column of users , I understand that if I establish relations in migrations and in the models when I want to register a new user, the user_id column in characters is automatically populated with the id of the newly registered user.

I would like to know if I am wrong and if that was perhaps a thousand apologies and thanks.

PD1: code of the migrations and models which I mention:

Model User.php:

   protected $fillable = [
        'name',
        'email',
        'password',
    ];
    public function characters()
    {
        return $this->hasOne('App\Character');
    }

Model Character.php:

    protected $fillable = [
     'user_id',
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

Migration characters:

public function up()
    {
        Schema::create('characters', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();

    $table->foreign('user_id')
            ->references('id')->on('users')
            ->onDelete('cascade');

PD2: As a temporary solution, get the same form that registers also authenticate the newly created account and using the facade Auth I can access the id of the authenticated user and fill in that way the column user_id in characters but I do not know if that's right.

    
asked by Ignacio Zsabo 14.08.2017 в 17:23
source

1 answer

2

Considering that it is a one-to-many relationship, the correct syntax for the relationship in the User model should be as follows:

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

As for how to save the relationship, the "Laravel method" would be something like that, creating the User first, then the character and finally the relationship, all this in the controller, or where you have the logic of this section located:

$nuevoUsuario = User::create(['name' => 'ignacio zsabo', 'email' => '[email protected]', 'password' => 'encriptada']);

$nuevoCaracter = Character::create(['name' => 'My weird character']);

$nuevoUsuario->characters()->save($nuevoCaracter);
    
answered by 15.08.2017 / 05:35
source