Update related tables laravel

1

I have been looking at the documentation for a while and I think it is correct, however it does not work as it should, instead of updating me, it creates a record.

The theme is as follows. I have a table with sellers and others with products, the idea is to update a product from a certain vendor.

These are the data.

The route

Route::resource('vendedor.producto', 'vendedor\vendedorProductoController',['except' => ['create','show','edit']]);

and the structure of the route when we put it in the browser becomes like this.

vendedor/{vendedor}/producto/{producto}

In my case, for example, it would be something like that

vendedor/95/producto/100

which would be that of seller 95 update the product 100

the seller model

class vendedor extends User
{


    protected $table = 'vendedores';



    public function productos()
    {
        return $this->hasMany('App\modelos\producto');
    }
}

the products model

    class producto extends Model
    {
       use SoftDeletes;

       protected $table = 'productos';

       protected $dates = ['deleted_at'];

       protected $hidden = ['pivot','deleted_at'];

       const PRODUCTO_DISPONIBLE = 'disponible';
       const PRODUCTO_NODISPONIBLE = 'no_disponible';

       protected $fillable = ['nombre','descripcion','cantidad','status','imagen','vendedor_id'];

       public function estaDisponible()
       {
         return $this->status == product::PRODUCTO_DISPONIBLE;
       }

       public function categorias()
       {
          return $this->belongsToMany('App\modelos\categoria');
        }

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

       public function transacciones()
       {
          return $this->hasMany('App\modelos\transaccion');
       }

}

The controller with the update method

public function update(Request $request, $idvendedor)
    {
        $vendedor = vendedor::findorfail($idvendedor);


        $datos = [
            'nombre' => $request->nombre,
            'descripcion' => $request->descripcion,
            'cantidad' => $request->cantidad,
            'imagen' => '1.jpg',
           'vendedor_id' => $vendedor->id,

                ];
        $producto =new producto($datos);


        $vendedor->productos()->save($producto);



    }

Well, do not update it, simply create a new record as if it were the store method

---------------- EDITION1 ------------------------------ --------------------------

I have made some modifications to the code and it still does not work.

I put the modifications

public function update(Request $request, $idvendedor,$idproducto)
    {
        $vendedor = vendedor::findorfail($idvendedor);
        $producto = producto::findorfail($idproducto);


        //$producto = new producto();

        $producto->nombre = $request->nombre;
        $producto->descripcion = $request->descripcion;
        $producto->cantidad = $request->cantidad;
        $producto->imagen ='9999.jpg';
        $producto->vendedor_id = $vendedor->id;


        $vendedor->productos()->save();


    }

In theory it has to work with this line

$producto = producto::findorfail($idproducto);

instead of this

 //$producto = new producto()

but I have commented it simply so that you see that I have used both options and it does not work for me, the error that gives me is this

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model

And here is the migration in case it clarifies something

PRODUCT MIGRATION

 public function up()
    {
        Schema::create('productos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre');
            $table->string('descripcion');
            $table->integer('cantidad')->unsigned();
          $table->string('imagen');
            $table->integer('vendedor_id')->unsigned();
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('vendedor_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        });
    
asked by KurodoAkabane 10.08.2017 в 19:49
source

3 answers

3

The error that shows you currently is because you are missing the input parameter: For the save method to work in a relation, you must put the model you want to save as an input parameter, HOWEVER this will not update the record, this will create a new one:

    $vendedor = vendedor::findOrFail($idvendedor);
    $producto = producto::findOrFail($idproducto);

    $producto->nombre = $request->nombre;
    $producto->descripcion = $request->descripcion;
    $producto->cantidad = $request->cantidad;
    $producto->imagen ='9999.jpg';
    $producto->vendedor_id = $vendedor->id;

    // para agregar un nuevo modelo a la relación, es necesario pasarlo como parámetro en save
    $vendedor->productos()->save($producto);

Solution to the problem of updating a product :

Your real problem is not being able to update a certain product for a certain vendor, however, the main key of the Product model is its id, so you do not need the least (in this case) the id of the seller to Update the product:

    $vendedor = vendedor::findOrFail($idvendedor);
    $producto = producto::findOrFail($idproducto);

    // nuevos valores...
    $producto->nombre = $request->nombre;
    $producto->descripcion = $request->descripcion;
    $producto->cantidad = $request->cantidad;
    $producto->imagen ='9999.jpg';
    $producto->vendedor_id = $vendedor->id;

    // guardar producto
    $producto->save();
    
answered by 11.08.2017 / 17:08
source
1

You can try it in the following way and verify that the% co_of% if it is coming

$vendedor = vendedor::findOrFail($idvendedor);

$producto = new producto();

$producto->nombre = $request->nombre;

$producto->descripcion = $request->descripcion;

$producto->cantidad = $request->cantidad;

$producto->imagen = '1.jpg';

$producto->vendedor_id = $vendedor->id;

$vendedor->productos()->save();
    
answered by 10.08.2017 в 23:14
1

Good morning: If you want to be updated, instead of using

$producto = new producto();
$vendedor->productos()->save($producto);

Why do not you use?

use App\Producto;
....
$producto = Producto::where('vendedor_id', '=', $vendedor->id)->first();
$producto->save();

Because from what I understand, you just want to update a product of a particular seller, right?

    
answered by 11.08.2017 в 12:11