Save an array in an Eloquent table

0

Hello, how could I save this request in a table called Cat_favoritas

which the arrangement of categories comes from a checkbox

array:3 [▼
  "_token" => "mqBPCysHUomaBF52LUMisDvI4Ptx5ygYQL1MQOj3"
  "categoria" => array:3 [▼
    0 => "2"
    1 => "3"
    2 => "1"
  ]
  "user_id" => 6
]

It turns out that according to the checkbox that the user checks, the controller receives them

   <label class="selectgroup-item">

<input type="checkbox" name="categorias[]" value="{{$categoria->id}}" class="selectgroup-input" checked>

		                
   <span class="selectgroup-button">{{$categoria->nombre}}</span>
</label>

but I have 3 tables

| Users | Categorias | Cat_favoritas |

First in the view it shows all the available categories, after having selected just I am trying to save it in Cat_favoritas

I've been trying using SYNC but I do not know how to translate it

My models and their relationships

| user |

   public function Cat_Favorita()
    {
        return $this->hasMany(Cat_favorita::class);

    }

Category Model

    public function Cat_favorita()
    {
     	return $this->HasMany(Cat_favorita::class);
    }
    

And finally the model Cat_favorita

	public function Categoria()
	{

	   return $this->belongsToMany(Categoria::class,'categoria_id');
	}

	public function User()
	{
		return $this->belongsToMany(User::class,'user_id');
   }
   
   No estoy seguro que esto este bie. 
    
asked by Alex Burke Cooper 26.09.2018 в 19:14
source

1 answer

1

It turns out that my relationships were wrong:

user model stayed like this.

I had a user who has many favorites but it is not like that. Actually my model should be like this:

    public function Categorias()
    {
        return $this->belongsToMany(Categoria::class,'cat_favoritas');

    }

where it says cat_favoritas. is the table where all my relationships will be stored according to my favorite categories:

Then the model categories stayed like this.

   public function categorias() {

     return $this->belongsToMany(User::class,'cat_favoritas');

   }

again. where it says ca_favoritas. is the name of my table where all my relationships are going to be stored.

now

in the controller this way I'm

auth()->user()->Categorias()->sync($request->get('categorias'));

And then it works!

    
answered by 26.09.2018 / 20:59
source