0

I'm new to laravel and I'm making a small api with just two tables to start. I have roles and people. I want to assign a role to a person from the store method but I don't understand how associate() works or how to implement it in the store method, this is what i have;

Model Rol:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Role extends Model
{
    

    use HasFactory;

    protected $fillable = ['id', 'rol'];

    public function personas()
    {
        return $this->hasMany(Persona::class);

        
        
    }


    
}

Model Persona:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Role;

class Persona extends Model
{
    use HasFactory;

    protected $fillable = ['id', 'nombres', 'apellidos', 'rol_id'];


    public function rol()
    {

        return $this->belongsTo(Role::class, 'rol_id');
        
    } 

    

    
}
$rol = Role::find(1);
    $persona->rol()->associate($rol);
    $persona->save();

Persona controller store method:

 public function index()
    {
        return PersonaResource::collection(Persona::with('rol')->paginate(25));
    }

    

    public function store(Request $request)
    {

        //$rol = Role::find(1);

        $persona = new Persona();

        // datos que voy a guardar
        $persona->nombres = $request->nombres;

        $persona->apellidos = $request->apellidos;

        $rol = new Role();
        
        //$rol->personas()->save($rol);
        $persona->rol()->save($rol);
    }

Btw i use postman, i am sending the data in this way (I don't know if it is the correct one) :

I want to know how to correctly associate both models to be able to correctly save the related data

ari127
  • 103
  • 3

0 Answers0