Laravel 5.4 - Update in related tables

1

What is the best way to do a update on two tables at the same time? I thought it was just calling the related table, but when I do this it just does the update in the service table and not the client table.

I was able to do this by passing the client id to view and then grabbing it and entering where to do the update another example), but I would like to know if it is possible to do update in both tables without getting 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 SERVICO

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');
    }
}
    
asked by anonymous 05.10.2017 / 16:17

1 answer

3

Load $servico , update fields, browse cliente() and update Cliente 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

    
05.10.2017 / 16:23