Laravel 5.4 - Update in related tables

Asked

Viewed 889 times

1

What’s the best way to make one update in two tables at the same time? I thought it was just to call the related table, but when I do it only makes the update on the table service and not in the client.

I managed to pass the customer id to view and then taking it and inserting it into Where to make the update(as shown by the other example), but I would like to know if it is possible to do the update in both tables without informing the foreign key code.

CLIENT CONTROLLER (Running)

public function update(Request $request, $id)
{
    $dataForm = $request->all();
    $cliente_id = $request->input('cliente_id');

    Servico::find($id)->update($dataForm);
    Cliente::find($cliente_id)->update($dataForm);

    return redirect()->route('index');
}

CLIENT CONTROLLER (Not working)

  public function update(Request $request, $id)
   {
        $dataForm = $request->all();

        Servico::with('cliente')->find($id)->update($dataForm);

        return redirect()->route('index');
   }

CUSTOMER MODEL

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Cliente extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'clientes';
    protected $fillable = ['nome', 'fone'];
    protected $dates = ['created_at', 'updated_at'];
    public $timestamps = true;

    public function servicos()
    {
        return $this->hasMany('App\Models\Servico');
    }
}

MODEL SERVICE

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Servico extends Model
{
    protected $primaryKey = 'id';
    protected $table = 'servicos';
    protected $fillable = ['valor', 'descricao', 'cliente_id', 'data_fechamento'];
    protected $dates = ['created_at', 'updated_at', 'data_fechamento'];
    public $timestamps = true;

    public function cliente()
    {
        return $this->belongsTo('App\Models\Cliente');
    }
}
  • Do you want Customer Service where 1 service is 1 customer?

  • That, a service belongs to 1 customer, but a customer can have several services.

  • When I edit a service, I can change the service information (value, description) and customer data(name, phone).

  • You can, Diego. Normally, just don’t forget to set up fillable!

  • It worked @Diego?

1 answer

3

Load the $servico, update the fields, navigate the relation cliente() and updates the Cliente of the relationship of Servico:

$servico = Servico::find($id) // busca o serviço
if ($servico) // verifica se serviço foi encontrado
{
    $servico->update($dataForm); // update serviço
    $servico->cliente()->update($dataForm); // update cliente da relação
}

Reference: Eloquent: updates

Browser other questions tagged

You are not signed in. Login or sign up in order to post.